Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What did Kernighan & Ritchie mean by 'Floating-point computations may now be done in single precision' in the new ANSI C standard?

On page 2 of The C programming Language by Kernighan & Ritchie, 2nd edition, in says that in the 'ANSI C' standard (as opposed to 'K&R C', which was defined in the first edition):

Floating-point computations may now be done in single precision.

What did they mean by that?

From Wikipedia and various Google search queries I've found that single precision in C means the 'float' data type (as opposed to 'double' data type which is a 'double precision'), but 'float' also appears in the first edition.

like image 294
J. Doe Avatar asked Dec 16 '25 12:12

J. Doe


1 Answers

They are talking largely about what we now call the "usual arithmetic conversions" (C17 6.3.1.8). This is a pattern of type conversions that is automatically applied to the operands of arithmetic operators. The stated primary objective is to bring the operands to a common type, but they also serve to reduce the number of distinct data types for which arithmetic operations must be implemented, and perhaps other purposes.

In the first edition of K&R, these are described on page 41, with the first provision being that (regardless of the other operand),

char and short are converted to int, and float is converted to double.

In that version of C, then, it is impossible to express a floating-point arithmetic operation performed at single precision (i.e. as a float), because float operands are converted to double whether you like it or not. For example, K&R 1ed specifies that this ...

    float x = 1;
    float y = 1;
    float z = x + y;

... is equivalent to this:

    float x = 1;
    float y = 1;
    float z = (double) x + (double) y;

All versions of standard C still specify that integer arithmetic operands of lower "integer conversion rank" than int are automatically converted to int or unsigned int, depending on various details. However, no version of standard C contained the K&R 1ed provision that float operands are automatically promoted to double. A float operand will be promoted to double if the other operand is a double, but not if the other is a float or any integer type.

Of course, that may be a distinction without much difference. The language spec doesn't have much to say about the details of floating point computation, so it is not necessarily the case that operations on floats behave any differently than by promoting the operands to double. In standard C, however, whether they do is a detail of the implementation, not a semantic requirement of the language.

like image 138
John Bollinger Avatar answered Dec 19 '25 07:12

John Bollinger



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!