I have the following part of C code:
char c;
int n = 0;
while ( (c = getchar()) != EOF ){
if (c == "\n"){
n++;
}
}
during compilation, compiler tells me
warning: comparison between pointer and integer [enabled by default]
The thing is that if to substitute "\n"
with '\n'
there are no warnings at all.
Can anyone explain me the reason? Another strange thing is that I am not using pointers at all.
I am aware of the following questions
- warning: comparison between pointer and integer [enabled by default] in c
- warning: comparison between pointer and integer in C
but in my opinion they are unrelated to my question.
PS. If instead of char c
there will be int c
there will be still warning.
'\n'
is called a character literal and is a scalar integer type."\n"
is called a string literal and is an array type. Note that arrays decay to pointers and so that's why you're getting that 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++;
}
}
Basically '\n' is a literal expression that evaluates to a char. "\n" is a literal expression that evaluates to a pointer. So by using this expression, you are effectively using a pointer.
The pointer in question is pointing to a region of memory that contains an array of characters (\n in this case) followed by a termination character that tells code where the array ends.
Hope that helps?
来源:https://stackoverflow.com/questions/13041701/c-comparing-char-to-n-warning-comparison-between-pointer-and-integer