如何在C中输入一个文字

Gün*_*ena 6 gcc casting literals gcc-warning

我有一个小样本函数:

#define VALUE 0

int test(unsigned char x) {
  if (x>=VALUE)
    return 0;
  else
    return 1;
}
Run Code Online (Sandbox Code Playgroud)

我的编译器警告我,比较(x> = VALUE)在所有情况下都是正确的,这是正确的,因为x是无符号字符,VALUE定义为值0.所以我将代码更改为:

if ( ((signed int) x ) >= ((signed int) VALUE ))
Run Code Online (Sandbox Code Playgroud)

但警告又来了.我测试了三个GCC版本(所有版本> 4.0,有时你必须启用-Wextra).

在更改的情况下,我有这个显式的强制转换,它应该是一个有符号的int比较.为什么声称这种比较总是正确的?

Mar*_*wis 12

即使使用演员表,在所有定义行为的情况下,比较仍然是正确的.编译器仍然确定(signed int)0其值为0,并且(signed int)x)如果您的程序已定义行为,则仍然确定它是非负的(如果值超出signed类型的值,则从unsigned转换为signed是未定义的).

所以编译器继续警告,因为它继续完全消除else情况.

编辑:要使警告静音,请将代码编写为

#define VALUE 0

int test(unsigned char x) {
#if VALUE==0
  return 1;
#else
  return x>=VALUE;
#endif
}
Run Code Online (Sandbox Code Playgroud)

  • `unsigned char`值可以*永远不会超出`signed int`的范围.即使设置了符号位,该值也在"signed int"的范围内,并且操作始终定义良好(结果始终为正). (3认同)
  • 糟糕,我错过了它从char到int.不过,这可能发生在C的(理论)实现上,其中sizeof(int)== 1.假设int必须至少有2个八位字节,那么在char也是两个八位字节的实现中这是可能的.我同意在现实的平台上,这里不会发生溢出. (3认同)

Cor*_*y D 7

xunsigned char,这意味着它是从0到256的由于int比更大char,浇铸unsigned charsigned int仍保留char的原始值.由于此值始终> = 0,因此您if始终为true.