开发者

Type of literal operands

I don't think most compilers care if, for instance, you do开发者_如何转开发n't append the f to a variable of float type. But just because I want to be as explicit and accurate as I can, I want to express the correct type.

What is the type of the result of two literal operands of different types, or does it depend on the circumstances? e.g.:

int i=1.0f/1;
float f=1.0f/1;

The compiler wouldn't complain in both these instances, is it because of its tolerant view of literal types or because the type of the result of the operation is always converted according to the context?


First, compilers do care about the f suffix. 1.0 is a double. 1.0f is a float. For instance:

printf("%.15f %.15f\n", 0.1f, 0.1);

produces 0.100000001490116 0.100000000000000 (note that the second number is not the real 0.1 any more than the first, it is just closer to it).

This matters not only to determine what numbers can and cannot be represented but also to determine the type of the operations this constant is involved in. For instance:

printf("%.15f %.15f\n", 1.0f/10.0f, 1.0/10.0);

produces the same output as before. What is important to notice here is that 1 and 10 are both representable exactly as float as well as as double. What we are seeing is not rounding taking place at the literal level, but the type of the operation being decided from the type of the operands.

Compilers are not being lenient about your examples. They are strictly applying rules that you can find in the relevant standard, especially sections 6.3.1.4 and 6.3.1.5.


The first one divides a float by an int, which always results in a float (as does dividing an int by a float). This float result is then converted into an int to be stored in i.

The second one takes the float that resulted from the operation, and assigns it to a float variable, preserving the floatness.

There are two separate issues here: How literals with or without suffixes are interpreted by the compiler, and the result of operations performed on mixed numeric types.


The type of literals is important in other contexts, for example (assuming f is a float):

f = f + 1.0;     // Cast `f` to double, do a double-precision add, and case the result back.

f = f + 1.0f;    // Single-precision addition.

Note that some compilers provide a relaxed mode, where both of them will generate the same code.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜