C comparing char to “\\n” warning: comparison between pointer and integer

痞子三分冷 提交于 2019-11-29 15:08:15
Pubby
  • '\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?

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!