0

I can't understand output of following C program, any idea ?

#include<stdio.h>

#include<conio.h>

void main()

{
  int a=5,b=6,c=11;

  clrscr();

  printf("%d %d %d");

  getch();
}

Output of this program is:

11 6 5

I can't understand why above program give us reverse variable values in printf I never declared which value have to print...So is there is any theory that if we no declared which variable have to print then we get reverse value of variables that we above declared in data type...

Magnus Hoff
  • 21,529
  • 9
  • 63
  • 82
Mr.FlaSh
  • 45
  • 3

5 Answers5

13

This is undefined behavior, and you should not expect a particular output (or an explanation of it), unless you care about implementation specific details.

What might be printed is the (random; i.e. "unpredictable") garbage value contained in some stack locations or registers supposed to hold the arguments.

BTW, some compilers (i.e. GCC when invoked with gcc -Wall) would give you some warning. Try hard to avoid them (by correcting the source code).

Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547
  • Is it like a lot of things fall under the bracket of undefined behaviour when it comes to C or there is a list to it? – Sid Aug 27 '13 at 07:18
  • 5
    I believe it is more important to understand the defined behavior (and semantics) of C than to try to enumerate all the possible cases of undefined behavior. – Basile Starynkevitch Aug 27 '13 at 07:20
4

printf uses stack to store and later print data. In this case first a goes in then b and then c.When printf pops out elements, first c comes out then b then a

goromlagche
  • 432
  • 1
  • 5
  • 12
2

There's a very good explanation right here. At runtime, the program will just print what's on the stack, which happens to be your variables.

Community
  • 1
  • 1
Noich
  • 14,631
  • 15
  • 62
  • 90
2

For your reference

int printf( const char* format, ... );

... - 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

As Joachim said the answer you got is by mere luck.You can't predict the exact results.

Community
  • 1
  • 1
Naren
  • 2,231
  • 1
  • 25
  • 45
0

Output of the above program vary depends on the compiler. Because it is undefined behavior.

Turbo C will give you the output you expected. Try to do some operation before doing printf. You will not get the output you expected. Because printf will print the recent stack entries.

If you compile the same program using gcc under linux, you will get warning.

sujin
  • 2,813
  • 2
  • 21
  • 33