Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strange GCC short int conversion warning

I have a bit of C code, which goes exactly like this:

short int fun16(void){
    short int a = 2;
    short int b = 2;
    return a+b;
}

When I try to compile it with GCC, I get the warning:

warning: conversion to 'short int' from 'int' may alter its value [-Wconversion]
  return a+b;
          ^

Though there is no visible conversion. Both operands are short and even the returning value is short as well. So, what's the catch?

like image 645
akalenuk Avatar asked Nov 27 '13 07:11

akalenuk


People also ask

How do I stop a GCC warning?

To suppress this warning use the unused attribute (see Variable Attributes). This warning is also enabled by -Wunused , which is enabled by -Wall . Warn whenever a static function is declared but not defined or a non-inline static function is unused.

What is werror?

-Werror= Make the specified warning into an error. The specifier for a warning is appended, for example -Werror=switch turns the warnings controlled by -Wswitch into errors.

Which flag would you pass to your C++ compiler so it warns you about implicit conversions?

By default, Fuchsia C/C++ code compiles with the flag -Wconversion , which prohibits implicit type conversions that may alter a value.

What is the job of werror option in GCC?

-Werror is a compiler flag that causes all compiler warnings to be treated as errors. Developers who enable -Werror are making a statement: we care about our code base, and we won't accept warnings here.


1 Answers

When you do arithmetic computations, the operands are subject to "the usual arithmetic conversions" (a superset of the "integer promotions" quoted in Acme's answer—he beat me to this but I'll go ahead and post anyway :-) ). These widen short int to plain int, so:

a + b

computes the same result as:

((int) a) + ((int) b)

The return statement must then narrow this int to a short int, and this is where gcc produces the warning.

like image 130
torek Avatar answered Sep 19 '22 20:09

torek