Usual arithmetic conversions in C : Whats the rationale behind this particular rule

929 views Asked by At

From k&R C

  • First, if either operand is long double, the other is converted to long double.
  • Otherwise, if either operand is double, the other is converted to double.
  • Otherwise, if either operand is float, the other is converted to float.
  • Otherwise, the integral promotions are performed on both operands; ...

This would mean below expression

char a,b,c;

c=a+b;

is actually caculated as

c = char((int)a+(int)b);

What is the rationale behind this rule?

Do these conversions happen if a, b and c were short ?

3

There are 3 answers

2
paxdiablo On BEST ANSWER

No that's not actually true. C99 Section 5.1.2.3 Program execution, clause 10 covers exactly the case you ask about:

EXAMPLE 2
In executing the fragment
char c1, c2;
c1 = c1 + c2;
the "integer promotions" require that the abstract machine promote the value of each variable to int size and then add the two ints and truncate the sum.

Provided the addition of two chars can be done without overflow, or with overflow wrapping silently to produce the correct result, the actual execution need only produce the same result, possibly omitting the promotions.

So, if the operation is known to produce the same result, there's no requirement for using the wider values.

But if you want the rationale behind a specific decision made in the standard, you have to look at, ..... wait for it, ..... yes, the Rationale document :-)

In section 6.3.1.8 of that rationale (sections match those in the standard), it states:

Explicit license was added to perform calculations in a “wider” type than absolutely necessary, since this can sometimes produce smaller and faster code, not to mention the correct answer more often.

Calculations can also be performed in a “narrower” type by the as if rule so long as the same end result is obtained.

2
Lundin On

Do these conversions happen if a, b and c were short ?

Yes, integer promotions are done on all small integer types: char, short and C99 bool.

Strictly speaking, a C program cannot perform any form of arithmetic on anything smaller than an int, unless the compiler optimizes away the integer promotions.

0
Basile Starynkevitch On

Several instruction set architectures do not have any arithmetic machine instructions to operate on less-than-a-word integers (like short and char). So requiring that convention makes thing simpler for the compiler. And most of the time, converting to word and operating on word-sized operands is enough.