-2
#include<stdio.h>
#include<conio.h>
void main()
{
int a=10,b=11;
clrscr();
printf("%d");
getch();
}

Output=11 How the output is 11 even I am not mentioned the variable name in the printf function.

user2683638
  • 21
  • 1
  • 3

2 Answers2

5

The 11 is on the stack because of the b variable, and your printf() function is looking on the stack for a value on the stack because that's where variables get passed.

If you add a c=47, you'll probably get 47. But this is undefined behavior.

Andy Lester
  • 91,102
  • 13
  • 100
  • 152
3

This is called "undefined behavior", which means that program can do just about anything.

What is actually happening in this case is that both variables and function parameters are put on the stack. Since you aren't passing the parameter that printf is expecting, it ends up pulling something else off the stack, which is your b variable.

But because it is undefined behavior, if you had a different compiler, a different CPU, or even different compile options, such as a higher optimization level, you could get very different results.

Vaughn Cato
  • 63,448
  • 5
  • 82
  • 132
  • Hello. Sorry for adding a question to a question. Shouldn't that `printf("%d");` be flagged as an error by the compiler ? – An SO User Sep 07 '13 at 16:32
  • It is flagged as an error if you turn on warnings. – vy32 Sep 07 '13 at 16:33
  • 1
    @LittleChild: The compiler isn't required to complain about this, although some do with the appropriate warning level. – Vaughn Cato Sep 07 '13 at 16:33
  • @rid It is a standard library function though so the compiler should be able to reason about it. I believe compilers are allowed to make assumptions about various library functions (particularly the standard math functions etc..) but I don't have a quote of the standard.. or maybe it's just GCC with its myriad function attributes.. – Thomas Sep 07 '13 at 16:36