Home > Mobile >  Why does comparing a string literal and an integer return a warning of comparison between pointer an
Why does comparing a string literal and an integer return a warning of comparison between pointer an

Time:08-19

int main()
{
   int c;
   c=getchar();
   if(c=="a")
   {
    printf("fizz");
   }
   else
    printf("buzz");
return 0;
}

Output:

test.c: In function 'main':
test.c:8:8: warning: comparison between pointer and integer
    if(c=="a")

As I understand it, if the string literal "a" was assigned to a variable name a[1] and the comparison was made c==a[0] then the variable name would implicitly decay into *a(0) which is a pointer to the first element in the array. But without a variable name how is the string literal "a" read as a pointer. Does the compiler itself assign a pointer to this string to execute the comparison?

CodePudding user response:

String literals have type "array of char". And like any array, when one is used in an expression it decays (in most cases) to a pointer to its first element.

So the comparison c=="a" is comparing an int on the left and a char * on the right, hence the warning.

CodePudding user response:

String literal is const char array which decays to a pointer.

So your code is almost identical to this one

   const char a[] = "a";
   c=getchar();
   if(c==a)

You need to use character constant

   c=getchar();
   if(c=='a')

or index the string literal

   c=getchar();
   if(c=="a"[0])
  • Related