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

后端 未结 5 2380
感动是毒
感动是毒 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:10

    The C language definition has been standardized and modified several times over the years. The original (non-standardized) version of C is known as "K&R C"; it's the language Kernighan and Ritchie originally developed.

    In 1989, ANSI created an official standards document (adopted in 1990 by ISO) to define the language, and in that standard some things were changed and extended; one of the changes is that the automatic promotion from float to double was removed.

    Since then, there have been two revisions to the standard, one in 1999 and one in 2011.

    I'm trying understand if I have an expression that mixes floats and doubles, can I rely on C to promote floats to doubles when it's evaluated?

    Here's the rule from the current standard:

    6.3.1.8 Usual arithmetic conversions

    ...
    First, if the corresponding real type of either operand is long double, the other operand is converted, without change of type domain, to a type whose corresponding real type is long double.

    Otherwise, if the corresponding real type of either operand is double, the other operand is converted, without change of type domain, to a type whose corresponding real type is double.

    Otherwise, if the corresponding real type of either operand is float, the other operand is converted, without change of type domain, to a type whose corresponding real type is float.62)
    62) For example, addition of a double _Complex and a float entails just the conversion of the float operand to double (and yields a double _Complex result).

    So basically, if you have an expression with two different types, the operand with the narrower/less precise type will be promoted to the type of the operand with the wider/more precise type.

提交回复
热议问题