C将char与"\ n"进行比较警告:指针与整数之间的比较 [英] C comparing char to "\n" warning: comparison between pointer and integer

查看:437
本文介绍了C将char与"\ n"进行比较警告:指针与整数之间的比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有C代码的以下部分:

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]

问题是,如果将"\n"替换为'\n',则完全没有警告. 谁能解释我的原因?另一个奇怪的事情是我根本没有使用指针.

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.

我知道以下问题

  • 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.如果不是char c而是int c仍会警告.

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

推荐答案

  • '\n'被称为字符文字,并且是标量整数类型.

    • '\n' is called a character literal and is a scalar integer type.

      "\n"被称为 string 文字,并且是数组类型.请注意,数组会衰减到指针,所以这就是为什么会出现该错误的原因.

      "\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.

      这可以帮助您了解:

      // 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++;
          }
      }
      

      这篇关于C将char与"\ n"进行比较警告:指针与整数之间的比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆