0
#include <stdio.h> int main(void) { double a = 1234.5f; int b = 71; int c = 68; int d; printf("%d %d %d %d\n", a,b,c,d); return 0; } 

Output:

 0 1083394560 71 68 

Here, Why b is giving garbage value, while c is giving value of b and d is giving value of c even it is uninitialized?

2
  • 3
    Pay more attention to your compiler warnings. Mismatching format specifiers and input data causes undefined behaviour. Commented Oct 3, 2014 at 6:36
  • Dcoder, I have seen the compiler warnings, I have written the code intentionally, I just want to know the reason of it's bahaviour. Commented Oct 3, 2014 at 7:59

4 Answers 4

5

"%d" in format specifier expects int, but a has a type of double, so it's undefined behaviour.

One possibility of what can happen is, the compiler puts the variables one by one on the stack. If, on your platform, the size of double were 8 bytes and twice the size of int the compiler makes wrong assumption of where to read the values. But again, it's undefined behaviour, the compiler is free to do anything it wants with your code.

Sign up to request clarification or add additional context in comments.

Comments

2

Behaviour is undefined here. But if you use 32bt machine explanation is simple:

You print each element as int (%d). Int is 4 bytes. Double is 8 bytes and has different representation. All arguments are passed through stack to printf. So first 8 bytes is a, then 4 bytes b, then 4 bytes c, then 4 bytes d.
printf takes const char argument and retrieve arguments from stack according to it; first %d 4 bytes should by integer, but it finds there half of double and prints garbage. Then %d next int, but printf finds on stack second half of double (again garbage). Then %d, again 4 bytes. It finds b and print it. Then again %d 4-bytes integer, prints c. There are no % in string, so printf stops printing.

Comments

1

for printing double value format specifier should be %f not %d

printf("%f %d %d %d\n", a,b,c,d); 

Comments

0

You are using the format specifier for an int and passing an argument of type double.

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

instead of

printf("%f %d %d %d\n", a,b,c,d); 

When the arguments to printf don't correspond to the conversion specifier, you run into unspecified behavior.

From http://en.cppreference.com/w/cpp/io/c/fprintf

arguments specifying data to print. If any argument is not the type expected by the corresponding conversion specifier, or if there are less arguments than required by format, the behavior is undefined. If there are more arguments than required by format, the extraneous arguments are evaluated and ignored

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.