If I compile the following program with g++ and enable warnings for conversions (-Wconversion)
#include<stdint.h>
int main() {
uint16_t foo = 1;
foo += 1;
return 0;
}
I get a warning, warning: conversion to uint16_t from int may alter its value.
Fine, if the 1 in foo+=1 is interpreted as int, but what about:
foo+=static_cast<uint16_t>(1);
I get the same warning, shouldn’t the operator work when the types of both sides are the same, w/o converting to an int?
I got an explanation, it comes from C but this should be equally valid in C++:
Specify a number literal as 8 bit?
For arithmetic, all operands are promoted to
intif they are smaller. This explains the problem, and why it doesn’t trigger on initialization, or when casting explicitely, because the cast will be undone to calculate the sum withints.