简体   繁体   中英

C Floating point changes %d value every time executed

I tried to print float using %d (I know that this shouldn't be done. But every time re-run executable it gives out a different value)
My question is : Why does the printed value changes every time ? My System : Ubuntu 14.04 (64 bit) Compiler : 4.8.4 Here is the code:

#include<stdio.h>

int main(){
  float b = 12.3456;

  printf("%d\n",b);

}

Sample output:

4bh1@mybox:~/C-fi$ ./test 
-1629995944
4bh1@mybox:~/C-fi$ ./test 
1147348376
4bh1@mybox:~/C-fi$ ./test 
-1746005432
4bh1@mybox:~/C-fi$ ./test 
510102216
4bh1@mybox:~/C-fi$ 

Using the wrong format specifier for printf is a classic example of undefined behavior . That means the behavior is unpredictable and can't be depended on to be consistent from one run to the next. It could crash, it could print random values, or it could appear to work.

What's actually happening is an implementation detail of the compiler and architecture in question. But unless you're actually writing a compiler, there's not much use in digging into it.

If you're familiar with assembler, you could look at the compiled code to see what instructions it generated. Keep in mind however that different compilers (even the same compiler with different optimization settings) will most likely generate different assembly.

Probably floating-point value is passed via FPU register, but printf() tries to read integer from somewhere else, where it expects to see integer (stack or another register). And content of that place is unspecified. Strictly saying (as @dbush has mentioned) your code causes undefined behavior.

As indicated in the comments, this sounds like undefined behaviour , which explains (well, sort of) what's happening.

In case you want to read the internal representation of a float, or you want to do some low-level hacks on the number, there's simple ways to do so, for example:

union {
    float f;
    int i;
} n;

n.f = 12.3456;
printf("%d\n", n.i); // should be the same number each time

Note that this only works if float and int have the same size on your system, but that should be the case for most people. You could add an assert(sizeof(float) == sizeof(int)) if you want to be sure.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM