Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ integer conversion rules

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?

like image 324
Jem Tucker Avatar asked Feb 03 '16 13:02

Jem Tucker


1 Answers

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.

like image 75
Bathsheba Avatar answered Oct 09 '22 06:10

Bathsheba