C ++ Integer Transformation Rules

What are the rules used by C ++ to determine the type of an arithmetic expression with two different integer types?

In general, it is easy to solve the result, however, I came across cases with signed / unsigned ints that are confusing.

For example, both of the following are presented 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 type?

+5
source share
2 answers

All of this is clearly defined.

1 is a signed literal. In fact, if you want it unsigned , you will need to use hexadecimal or octal notation, the corresponding suffix (e.g. u ), or listing.

If an arithmetic operation occurs that has the arguments signed int and unsigned int , then signed int converted to unsigned int .

+5
source

Here is a short, crude answer, I hope it is useful, although it does not cover everything and may even be simplified:

  • Literals are signed unless indicated as "U".

  • In integral expressions that include different types, smaller integer types are encouraged (up to int if all the involved types match int, otherwise advance to unsigned int), therefore, when an unsigned value and a signed value, for example, are added, the signed value "moves forward "to unsigned int if the unsigned variable has the same bit width as int. Thus, the unsigned int is considered by the compiler to be β€œlarger” than the signed int in the promotion rules, even if at run time the actual values ​​stored in the variables easily fit into the signed representation of the same number of bits.

  • Note that 'char' can mean unsigned char, while 'int' always means signed int.

0
source

Source: https://habr.com/ru/post/1242203/


All Articles