Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
246 views
in Technique[技术] by (71.8m points)

c++ - How does this program work?

#include <stdio.h>

int main() {
    float a = 1234.5f;
    printf("%d
", a);
    return 0;
}

It displays a 0!! How is that possible? What is the reasoning?


I have deliberately put a %d in the printf statement to study the behaviour of printf.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

That's because %d expects an int but you've provided a float.

Use %e/%f/%g to print the float.


On why 0 is printed: The floating point number is converted to double before sending to printf. The number 1234.5 in double representation in little endian is

00 00 00 00  00 4A 93 40

A %d consumes a 32-bit integer, so a zero is printed. (As a test, you could printf("%d, %d ", 1234.5f); You could get on output 0, 1083394560.)


As for why the float is converted to double, as the prototype of printf is int printf(const char*, ...), from 6.5.2.2/7,

The ellipsis notation in a function prototype declarator causes argument type conversion to stop after the last declared parameter. The default argument promotions are performed on trailing arguments.

and from 6.5.2.2/6,

If the expression that denotes the called function has a type that does not include a prototype, the integer promotions are performed on each argument, and arguments that have type float are promoted to double. These are called the default argument promotions.

(Thanks Alok for finding this out.)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...