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

后端 未结 3 402
时光取名叫无心
时光取名叫无心 2021-01-21 17:14

From k&R C

  • First, if either operand is long double, the other is converted to long double.
  • Otherwise, if either o
3条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-21 17:57

    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.

提交回复
热议问题