I do apologize if this question has been answered somewhere else, but I've searched, and have not yet found an answer...
I get the following warning when compiling the code below:
warning: conversion to 'short unsigned int' from 'int' may alter its value
Here is an excerpt of code (several examples to illustrate my question):
std::vector<unsigned short int> list = {1};
unsigned short int one = 1;
one += list.at(0); // produces warning
one += 1; // produces warning
one += static_cast<unsigned short int> 1; // produces warning
one++; // does not produce warning
I've also tried other forms of arithmetic besides addition. Why does the compiler throw this warning, claiming that I'm converting to an 'unsigned short int' from an 'int' (especially when I've explicitly cast it as unsigned)? It would also seem, that for the second case, 'one += 1;', since the right side of the expression is a positive number, the compiler wouldn't have any problem adding it to the unsigned variable 'one'.
Also, the final test, 'one++;' does not produce a warning, and I'm not sure why.
I'm still getting used to asking questions on here, so forgive me if this question is trivial or unclear. Thanks!
C++11 §5.17/7:
”
The behavior of an expression of the formE1
op= E2
is equivalent toE1 = E1
opE2
except thatE1
is evaluated only once
This means that e.g.
one += list.at(0);
is evaluated as if it were
one = one + list.at(0);
except that one
is evaluated only once.
In the expresseion one + list.at(0)
both operands are first promoted to int
, by C++11 §5/9, the usual arithmetic conversions rule.
In short, C++ binary arithmetic operators do not deal with operands of types with potentially smaller range than int
. The operands are promoted. And then for the final assignment, there is (logical) conversion back down.