Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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: " << 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.

like image 434
anatolyg Avatar asked Jan 02 '11 18:01

anatolyg


People also ask

How do I enable warnings in GCC?

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 .

How do I turn off warnings in GCC?

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).

How do I turn off compiler warnings?

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.

Which GCC flag is used to enable all compiler warnings?

gcc -Wall enables all compiler's warning messages. This option should always be used, in order to generate better code.


2 Answers

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.

like image 134
Vikram.exe Avatar answered Sep 23 '22 22:09

Vikram.exe


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
like image 35
Martin v. Löwis Avatar answered Sep 23 '22 22:09

Martin v. Löwis