My notes on Integer promotion, arithmetic conversions in C

Integer Promotions:

Integer types smaller than int are promoted when an operation is performed on them. If all the values of the original type can be represented as an int, the value of the smaller type is converted to an int; otherwise it is converted to an unsigned int.

E.g.:

char c1, c2;
c1 = c1 + c2;
c1 and c2 gets promoted to integer , sum is calculated and then truncated to fit into char type.

signed char cresult, c1, c2, c3;
c1 = 100;
c2 = 3;
c3 = 4;
cresult = c1 * c2/c3;

Assuming that signed char is represented as 8-bit value, Integer promotion happens c1, c2 and c3 are promoted to int. Finally the result is truncated to char which is 75.

char a = 30, b = 20, c = 10;
 char d = (a * b) / c;

a, b and c are promoted to integer, operation is performed on them and finally the result is truncated to char which is 60, no data is lost in this case

The logic behind integer promotion is to avoid accidental overflows during arithmetic operations.

Mixed Mode Arithmetic:

When operands in an expression contains both integer and float variables, it is mixed mode arithmetic.

In mixed mode arithmetic, integer operands are always converted to float, before carrying out any computations. The result of mixed mode arithmetic is always float.

E.g.
1 + 3.5 = 4.5
1/4.0 = 0.25

Explicit Type Conversion:

In some situations, the type of expression (r-value), and the type of the value (l-value) may not be same, in such case r-value may be promote or demote automatically to the l-type.

E.g.

1. int x;
x = 12.45;
printf("%d\n", x);
O/P: 12
Real value demoting to int

2. float x;
x = 5/2;
printf("%f\n", x);
O/P: 2.0000
5/2 is integer arithmetic and the result is integer, it is promoted to float

The above can be rectified by adding fractional part .0
x = 5.0/2;
O/P: 2.50000

But we cannot use '.0' always, as it can only be added to constants, but not to variables. In this case we must explicitly convert it to float.

Syntax: (type) variable.

x = (float)a/b;

x = a/(float)b;

In general, arithmetic operations that combine signed and unsigned values yields an unsigned result. This property is particularly important for comparisons, in which a signed integer is converted to unsigned integer for comparison purposes.

E.g comparison i >= 0u, where 0 u is unsigned zero is always true, even if i is unsigned int, because i is converted to unsigned and the result of that is never negative.





Comments

Popular posts from this blog

bb.utils.contains yocto

Difference between RDEPENDS and DEPENDS in Yocto

PR, PN and PV Variable in Yocto