开发者

No warning on assignment of int to short (gcc)

I often use assignment of "longer" typed variables to "shorter" ones, for example int to short or uint32_t to uint8_t. One day i decided to find all such cases in my code using gcc, but found to my amazement that gcc didn't output any warnings!

int long_value;
short short_value;
std::cin >> long_value; // Example input: 32769
short_value = long_value; // MS Visual Studio complains here at warning level 4
std::cout << "Long: " << long_value << '\n'; // My example output: 32769
std::cout << "Short: " <<开发者_如何学Go; short_value << '\n'; // My example output: -32767

Using gcc -Wall or gcc -Wconversion didn't help (gcc didn't output any warning). Actually, it never output any warning for any input and output type (e.g. long and unsigned char).

I have never found an actual bug in gcc so i am almost sure this behavior has a reason.

So why no warning?

Update: i use gcc 4.1.2.


This feature was added in gcc 4.3 version. Previously this was not available.

I hope you are using gcc version 4.2 or below.

http://gcc.gnu.org/wiki/NewWconversion confirms this.

This bug: http://gcc.gnu.org/bugzilla/show_bug.cgi?id=2707 also talks about it.


I can't reproduce that. Compiling this code with gcc 4.4.5 with -Wconversion, I get

a.cc: In function ‘void f()’:
a.cc:7: warning: conversion to ‘short int’ from ‘int’ may alter its value
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜