C programming: Does float always auto-convert to double when multiplying mixed data types?

后端 未结 5 2427
感动是毒
感动是毒 2021-02-20 14:17

In Steven Prata\'s book \"C Primer Plus\", there\'s a section on Type Conversions, wherein \"The basic rules are\" section has stated in rule 1:

Under K&R C,         


        
5条回答
  •  谎友^
    谎友^ (楼主)
    2021-02-20 15:01

    Look at the entire rule:

    When appearing in an expression, char and short, both signed and unsigned, are automatically converted to int or, if necessary, to unsigned int. (If short is the same size as int, unsigned short is larger than int; in that case, unsigned short is converted to unsigned int.) Under K&R C, but not under current C, float is automatically converted to double. Because they are conversions to larger types, they are called promotions.

    If we consider the integer types, when they appear in e.g. arithmetic expressions, they are still promoted, so no arithmetic is -theoretically - performed at the types char or short, but all at type int, unsigned int or a type with higher conversion rank (under the as-if rule, if the implementation can guarantee that the result is the same as if the promotion were actually carried out, it can perform arithmetic at smaller types if the platform provides the instructions).

    The analogous used to hold for float, under the old pre-standard rules, floats were promoted to double for all arithmetic etc.

    That is no longer the case, arithmetic on floats does not involve automatic promotion under standardised C.

    In expressions with mixed types, generally everything is still promoted to the largest involved type, so if you compare or add a float to a double, the float is converted to double before the operation.

提交回复
热议问题