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

后端 未结 3 403
时光取名叫无心
时光取名叫无心 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:56

    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.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-01-21 18:15

    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 讨论(0)
提交回复
热议问题