Comparison of characters in C
I have a question about comparing a single char string in C inside a function. The code looks like this:
int fq(char *s1){
int i;
for(i=0;i<strlen(s1);i++){
if(s1[i]=="?"){
printf("yes");
}
}
return 1;
}
Even if s1 = "???" it never prints out yes. I was able to solve the problem, but I'm curious why it works in one direction but not the other. This is the piece of code that works:
int fq(char *s1,char *s2){
int i;
char q[]="?";
for(i=0;i<strlen(s1);i++){
if(s1[i]==q[0]){
printf("yes");
}
}
return 1;
}
source to share
As the first sample compares addresses instead of characters.
There is ==
no string type in c and operator , when applied to an array or pointer, it compares addresses instead of content.
Your function will be correctly written as follows
int fq(char *s1,char *s2)
{
int i;
for (i = 0 ; s1[i] ; ++i)
{
if (s1[i] == 'q')
printf("yes");
}
return 1;
}
you can compare s1[i]
with 'q'
.
source to share
if(s1[i]=="?"){
is not the correct syntax to test if it is a s1[i]
character '?'
. It should be:
if(s1[i] == '?'){
You might want to figure out how you can change compiler options so that you get warnings when such expressions exist in your code base.
Using the -Wall
c option gcc
, I get the following message:
cc -Wall soc.c -o soc soc.c: In function ‘fq’: soc.c:7:15: warning: comparison between pointer and integer if(s1[i]=="?"){ ^ soc.c:7:15: warning: comparison with string literal results in unspecified behavior [-Waddress]
source to share
In a C character array, that is, the string has the syntax like "". For one character, the syntax is ''.
In your case: it should be: if(s1[i]=='?')
If you want to compare it in string form, you need strcmp. Since the '==' operator is not capable of comparing strings in C.
To compare two strings, we can use: if(!strcmp(s1,q))
And for this operation, you need to add a string.h header like: #include <string.h>
To compare strings with the '==' operator, you need to overload the operator. But C doesn't support operator overloading. You can use C ++ language for this.
source to share