开发者

floating constants in C

I have a question concerning floating constants in C.

In Java, the defaul开发者_运维知识库t type of floating point constants in double, so the following will causes a compilation error in java:

float f = 100.0;   // we either need to uses type case operator or put f at the end of the number constant.

This is because the default floating-point constants are of type double and casting from double to float without type cast operator is an error, so we need either add a type case operator or put f at the end of the number.

So, Why in C this doesn't produce an error, Is it because the default floating-point constants are of type float, or because the compiler do an implicit down-cast conversion (that doesn't requires type case operator in C)????


In C, floating point constants have type double by default, but a double can be implicitly converted to a float (note that you do have to be careful: if the value of the constant is outside the range representable by a float, the result of such a conversion is undefined).

If you want a floating point constant of type float, you can append the suffix f to the end of the constant.


Unsuffixed floating-point constants are double in C too. See §6.4.4.2 of the standard:

You are right that it narrows here:

§6:3.1.5:

"When a double is demoted to float, a long double is demoted to double or float, or a value being represented in greater precision and range than required by its semantic type (see 6.3.1.8) is explicitly converted to its semantic type, if the value being converted can be represented exactly in the new type, it is unchanged. If the value being converted is in the range of values that can be represented but cannot be represented exactly, the result is either the nearest higher or nearest lower representable value, chosen in an implementation-defined manner. If the value being converted is outside the range of values that can be represented, the behavior is undefined."

§6:5.16:

"The type of an assignment expression is the type of the left operand [...]"

§6:5.16.1:

"In simple assignment (=), the value of the right operand is converted to the type of the assignment expression and replaces the value stored in the object designated by the left operand."


C silently downcasts double to float. And, as already pointed out, a floating point literal is assumed to be a double.

In gcc, the compiler option -Wconversion (not implied in -Wall) gives a warning for this downcasting (for example in a literal assigment, as in your question).

warning: conversion to 'float' from 'double' may alter its value

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜