Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing characters in C

I have a question about comparing a single char of a 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 have managed to solve the problem but i am curious as to why it works one way 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;
}
like image 634
Shivalnu Avatar asked Aug 30 '26 00:08

Shivalnu


2 Answers

Because the first sample compares addresses instead of characters.

There is no string type in c and the == operator when applied to an array or a pointer, compares the addresses instead of the contents.

Your function would be correctly written like this

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] to 'q'.

like image 176
Iharob Al Asimi Avatar answered Aug 31 '26 14:08

Iharob Al Asimi


"?" Isn't a char but a string with just one char

'?' Is a char and should return true in s1[i] == '?'

like image 24
KM11 Avatar answered Aug 31 '26 12:08

KM11



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!