Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why does comparing a string literal and an integer return a warning of comparison between pointer and integer?

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading