c - 转换未更改值时发出警告

标签 c gcc compiler-warnings

考虑这个程序:

int main() {
  int ju = 1;
  short ki = ju;
  return ki;
}

编译产生警告:

conversion to ‘short int’ from ‘int’ may alter its value [-Wconversion]
   short ki = ju;
              ^

然而根据to the docs :

Do not warn [...] if the value is not changed by the conversion like in "abs (2.0)".

我们正在处理1的值,它可以很容易地存储在int。该值未因转换而更改,那么为什么会出现警告?

最佳答案

忽略任何可能的编译器优化:

int main() {
  int ju = 1;
  short ki = ju; /* Compiler won't [probably] make use of (without optimizations) what the value of ju is at runtime */
  return ki;
}

另一个例子(即使使用编译器优化,也无法确定 ju 在编译时分配给 ki 时的值是什么):

int foo() {
  int ju = 1;
  short ki = 1;

  scanf("%d", &ju);

  ki = ju; /* (Compiler will issue the warning) What's the value of ju? Will it fit in ki? */

  return ki; /* Another implicit conversion, this one from short to int, which the compiler won't issue any warning */
}

编译器不知道 ju 的值是多少,因此它会正确地警告隐式类型转换。

关于文档,并引用您的问题:

Do not warn [...] if the value is not changed by the conversion like in "abs (2.0)".

int foo() {
  return 0UL;
}

这是一个示例,无论涉及何种类型,值都不会改变。零将始终为零,无论是 int 还是 unsigned long 类型。

或者,

int foo() {
  return 2.0; /* Same case as abs(2.0), an implicit float to int convertion, whose values are not changed by doing so. */
}

因此,基本上,这仅适用于文字(例如文档中给出的 abs(2.0) 示例)。

关于c - 转换未更改值时发出警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38287363/

相关文章:

c - union 和位掩码,这是如何工作的?

c++ - 关于非普通旧数据上的 memset 的编译时间警告

c++ - 为什么在声明对象 std::vector 但从未使用时编译器不发出警告?

c - 在 Linux 中使用 c 私有(private)内存使用量不断增加

c++ - 如何在没有任何依赖库的情况下在 Visual Studio 中构建 dll?

c - 输入两个字符串后列出目录的路径名

c - 如何将c程序编译为dll

linux - 为什么 gcc 默认链接 '-z now',尽管延迟绑定(bind)是 ld 的默认值?

c - 编译器生成的汇编代码中的.LFB .LBB .LBE .LVL .loc是什么

c++ - MSVC -Wall 标准标题中的数千条警告是怎么回事?