I need to eliminate gcc -Wconversion warnings. For example
typedef unsigned short uint16_t;
uint16_t a = 1;
uint16_t b = 2;
b += a;
gi
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.
You could build your own abstraction to overload the +=
operator, something like
template <typename T>
class myVar {
public:
myVar(T var) : val{var} {}
myVar& operator+=(const myVar& t) {
this->val = static_cast<T>(this->val + t.val);
return *this;
}
T val;
};
int main()
{
typedef unsigned short uint16_t;
myVar<uint16_t> c{3};
myVar<uint16_t> d{4};
c += d;
}
It still uses a static_cast
, but you only need to use it once and then reuse it. And you don't need it in your main
.
IMHO it just adds overhead, but opinions may vary...