What are the rules used by C++ to determine the type of an arithmetic expression involving two different integer types?
In general it is easy to work out the outcome, however I have come across cases with signed/unsigned ints that are confusing.
For example both the below come out as unsigned int
in VS.
unsigned int us = 0;
int s = 1;
auto result0 = us - s; // unsigned int
auto result1 = s - us; // unsigned int
Is this the same for other compilers? Are there any specific rules for determining the type?
It's all well-defined.
1
is a signed literal. In fact, if you wanted it unsigned
, you'd need to use hexadecimal or octal notation, an appropriate suffix (for example u
), or a cast.
If an arithmetic operation is encountered that has a signed int
and an unsigned int
as arguments, then the signed int
is converted to an unsigned int
type.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With