-3
int a=9,b=6,c=3;
printf("%d%d%d");

I executed this in code blocks 10.05. I got some garbage values. But in a website the output was given as 3 6 9. What is the correct one?

3 Answers3

3

You will get garbage values, because you're not providing any arguments to the printf() call.

The correct code would be

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

(to get the numbers in the order quoted)

ahnlak
  • 41
  • 2
  • But the "garbage" values may indeed be a, b, and c's values; the point is that what is actually printed is undefined. It may indeed be "3 6 9", but it could be anything else, as well. – Ernest Friedman-Hill Aug 29 '13 at 13:15
  • True - I suppose strictly speaking the answer to the question "which is the correct output" is that it's undefined. However, I assumed that the OP wanted to know what was causing the behaviour he didn't expect rather than a technically correct but less informative response :) – ahnlak Aug 29 '13 at 13:27
  • @ErnestFriedman-Hill The local variables are stored in stack. So when `printf()` is invoked, it search for the _variable reference_ in that stack examining its type. But if any variable name is not provided, then it fails to map the **format specifier** with the variable name then directly fetch the value from stack in FIFO order. – joy-cs Aug 29 '13 at 17:40
  • 2
    That's pretty much gibberish. – Ernest Friedman-Hill Aug 29 '13 at 18:47
2

The correct one is neither of the two you described. Since no values were passed to printf, only the formatters, whatever was on the stack at that moment (which is undefined) is passed.

sidyll
  • 57,726
  • 14
  • 108
  • 151
0

What is the correct output of this statement?

This code invokes undefined behaviour and so there is no correct output. The output is undefined.

The code invokes undefined behaviour because the format string you passed to printf requires you to pass more parameters (3) than you supplied (0).

David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490