Jem Tucker
Jem Tucker

Reputation: 1163

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?

Upvotes: 5

Views: 2136

Answers (2)

Erik Alapää
Erik Alapää

Reputation: 2713

Here is a short, rough answer, I hope it is useful even though it does not cover everything and may even be an oversimplification:

  1. Literals are signed unless specified as 'U'.

  2. In an integral expressions involving different types, the smaller integer types are promoted (to int if all involved types would fit in int, otherwise promotion to unsigned int), so when an unsigned and a signed value e.g. are added, the signed value is 'promoted' to unsigned int if the unsigned variable is of same bit width as an int. So an unsigned int is regarded by the compiler as 'larger' than a signed int in the promotion rules, even if during runtime the actual values stored in the variables would easily fit into a signed representation of same number of bits.

  3. Note also that 'char' may mean unsigned char, while 'int' always means signed int.

Upvotes: 1

Bathsheba
Bathsheba

Reputation: 234875

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.

Upvotes: 5

Related Questions