我有以下C代码部分:
char c;
int n = 0;
while ( (c = getchar()) != EOF ){
if (c == "\n"){
n++;
}
}
Run Code Online (Sandbox Code Playgroud)
在编译期间,编译器告诉我
warning: comparison between pointer and integer [enabled by default]
Run Code Online (Sandbox Code Playgroud)
问题是,如果替换"\n"
,'\n'
则根本没有警告.任何人都可以解释我的原因吗?另一个奇怪的事情是我根本不使用指针.
我知道以下问题
但在我看来,他们与我的问题无关.
PS.如果不是char c
将会int c
有警告.
'\n'
被称为字符文字,是标量整数类型.
"\n"
被称为字符串文字,是一种数组类型.请注意,数组会衰减为指针,因此您就会收到该错误.
这可能有助于您理解:
// 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++;
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
13256 次 |
最近记录: |