Why doesn't returning 0x80000000 from a function that returns int32_t cause a warning?

末鹿安然 提交于 2019-12-23 13:30:27

问题


Consider:

int32_t f() {
  return 0x80000000;
}

Why doesn't that cause a compiler warning (at least on GCC)? 0x80000000 is out of the range of int32_t (INT32_MAX is 0x7fffffff). I believe this should cause an implicit cast - is that correct?

Further consder:

if (f() == 0x80000000)
  foo();

The above causes no warning on GCC. However

int32 ret = f();
if (ret == 0x80000000)
   baz();

Causes "warning: comparison between signed and unsigned integer expressions". I believe this is because 0x80000000 has type unsigned int due to being out of int's range. Is that correct?

Assuming none of my assumptions are wrong, why doesn't the first comparison cause a warning?


回答1:


The relevant warning switch appears to be -Wconversion, which is not activated by -Wextra.




回答2:


I believe this is because 0x80000000 has type unsigned int due to being out of int's range. Is that correct?

Yes, since it's a hexadecimal integer literal, it's type would be the narrowest of these types capable of representing the value of the literal:

  • int
  • unsigned int
  • long
  • unsigned long
  • long long
  • unsigned long long


来源:https://stackoverflow.com/questions/32656460/why-doesnt-returning-0x80000000-from-a-function-that-returns-int32-t-cause-a-wa

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!