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

时间:2016-07-10 00:00:05

标签: 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

  

如果转换没有改变值,请不要警告[...]   “abs(2.0)”。

我们正在处理1的值,该值可以轻松存储在int或。{ short。转换不会更改该值,为什么会出现警告?

2 个答案:

答案 0 :(得分:1)

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

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

编译器无法知道int foo() { return 0UL; } 的值是什么,所以它正确地警告了隐式类型转换。

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

  

如果转换之类的值没有改变,请不要警告[...]   在“abs(2.0)”中。

int

这是一个示例,无论所涉及的类型如何,值都不会发生变化。零将始终为零,即unsigned longint 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)

所以,基本上,这仅适用于文字(例如文档中给出的urlpatterns = [ # ex) /snu/ url(r'^$', views.site_list, name='site_list'), # ex) /snu/cse/ url(r'^(?i)(?P<site_name>[a-zA-Z]+)/$', views.post_list, name='post_list'), # ex) /snu/cse/post/3 url(r'^(?i)(?P<site_name>[a-zA-Z]+)/post/(?P<pk>[0-9]+)/$', views.post_detail, name='post_detail'), # ex) /snu/cse/post/3/remove url(r'^(?i)(?P<site_name>[a-zA-Z]+)/post/(?P<pk>\d+)/remove/$', views.post_remove, name='post_remove'), # ex) /snu/upload url(r'^(?i)upload/$', views.upload, name='upload'), ] 示例)。

答案 1 :(得分:0)

short ki = ju;

属于

  

隐式转换可能会改变某个值[1]。

int 这是编译时已知的。

  

转换不会改变VALUE,为什么会出现警告?

这是你根据自己的直觉得出的结论。这些知识即使已知也不需要[2]编译时使用。

<强>参考

[ 1 ] gcc警告选项。

注意

[2]编译器无需跟踪存储在变量中的值。