Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
501 views
in Technique[技术] by (71.8m points)

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

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 ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...