Question

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

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.

Was it helpful?

Solution

  • '\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++;
    }
}

OTHER TIPS

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?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top