C comparison char with warning "\ n": comparison between pointer and integer

I have the following piece of C code:

char c; int n = 0; while ( (c = getchar()) != EOF ){ if (c == "\n"){ n++; } } 

at compile time, the compiler tells me

 warning: comparison between pointer and integer [enabled by default] 

The fact is that if you replace "\ n" with "\ n", there are no warnings at all. Can anyone explain the reason to me. Another weird thing is that I don't use pointers at all.

I know the following questions.

but, in my opinion, they are not related to my question

PS. If instead of char c; will be int c; there will be another warning

+4
source share
2 answers

\n' is called a character symbol and is an integer.

"\n" is called a string literal and is an array type. Please note that arrays decay into pointers and therefore you get this error.

This may help you understand:

  // analogous to using '\n' char c; int n = 0; while ( (c = getchar()) != EOF ){ int comparison_value = 10; // 10 is \n in ascii encoding if (c == comparison_value){ n++; } } // analogous to using "\n" char c; int n = 0; while ( (c = getchar()) != EOF ){ int comparison_value[1] = {10}; // 10 is \n in ascii encoding if (c == comparison_value){ // error n++; } } 
+8
source

Basically, "\ n" is a literal expression that evaluates to char. "\ n" is a literal expression that evaluates to a pointer. Thus, using this expression, you are effectively using a pointer.

The specified pointer points to a region of memory that contains an array of characters (\ n in this case), followed by a termination character, which tells the code where the array ends.

Hope this helps?

+1
source

Source: https://habr.com/ru/post/1441697/


All Articles