Integral promotion and operator+=

  • A+
Category:Languages

I need to eliminate gcc -Wconversion warnings. For example

typedef unsigned short     uint16_t;  uint16_t a = 1; uint16_t b = 2; b += a; 

gives

warning: conversion to 'uint16_t {aka short unsigned int}' from 'int' may alter its value [-Wconversion]      b += a;      ~~^~~~ 

I can eliminate this by

uint16_t a = 1; uint16_t b = 2; b = static_cast<uint16_t>(b + a); 

Is there any way to keep the operator+= and eliminate the warning? Thank you.

EDIT

I use

gcc test.cpp -Wconversion

my gcc version is

gcc.exe (Rev3, Built by MSYS2 project) 7.2.0

 


I need to eliminate gcc -Wconversion warnings.

You don't say why but this is actually unlikely.

From the GCC wiki page on this switch:

Why isn't Wconversion enabled by -Wall or at least by -Wextra?

Implicit conversions are very common in C. This tied with the fact that there is no data-flow in front-ends (see next question) results in hard to avoid warnings for perfectly working and valid code. Wconversion is designed for a niche of uses (security audits, porting 32 bit code to 64 bit, etc.) where the programmer is willing to accept and workaround invalid warnings. Therefore, it shouldn't be enabled if it is not explicitly requested.

If you don't want it, just turn it off.

Mangling your code with unnecessary casts, making it harder to read and maintain, is the wrong solution.

If your build engineers are insisting on this flag, ask them why, and ask them to stop.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: