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: " << 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.
Warn if an aggregate or union initializer is not fully bracketed. In the following example, the initializer for a is not fully bracketed, but that for b is fully bracketed. int a[2][2] = { 0, 1, 2, 3 }; int b[2][2] = { { 0, 1 }, { 2, 3 } }; This warning is enabled by -Wall .
To suppress this warning use the unused attribute (refer to Section 6.33 Specifying Attributes of Variables). Warn whenever a function parameter is unused aside from its declaration. To suppress this warning use the unused attribute (refer to Section 6.33 Specifying Attributes of Variables).
Turn off the warning for a project in Visual StudioSelect the Configuration Properties > C/C++ > Advanced property page. Edit the Disable Specific Warnings property to add 4996 . Choose OK to apply your changes.
gcc -Wall enables all compiler's warning messages. This option should always be used, in order to generate better code.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With