Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the output of the following code?

Tags:

c

int main()
{
  int x=5,y=10,z=15;
  printf("%d %d %d");
  return 0;
}

Output: 15 10 5 //In Turbo C 4.5

    3 Garbage values in gcc compiler

My teacher told me when we define the variables like int x=5,y=10,z=15; they are by default taken as auto type and stored in stack.When you try print 3 integer values without using their names by printf(), it will print those 3 values in LIFO format as Turbo C compiler does. But what I think when we define 3 integer variables, they may not be stored in continuous memory locations.So when I try to print 3 integer values without using their names, the compiler will print any three values from top of the stack.so the output will come 3 garbage values as in gcc..

like image 570
Parikshita Avatar asked Dec 01 '22 09:12

Parikshita


2 Answers

This code just shows that Turbo C is poor at optimizing code and puts everything on the stack, while gcc is more aggressive and keeps it in registers or throws it away all together because these three variables have no purpose.

Anyway, calling printf with a pattern that requires three arguments without providing these arguments, is a mistake.

Update:

As an explanation: I'm assuming that printf() will always take its argument from the stack since it's a function with a variable argument list. Or does anybody know any other calling convention for functions like printf()? Futhermore, I'm assuming there's no need to put anything else on the stack as there are no other variables. So this mistaken call of printf will print whatever is on top of the stack in main(). But there might be other architectures and calling conventions where my assumpations don't hold.

like image 103
Codo Avatar answered Dec 15 '22 07:12

Codo


This is undefined behavior.

With an optimizing compiler, these 3 values might be optimized out as they are not used. It will print garbage.

like image 36
Didier Trosset Avatar answered Dec 15 '22 06:12

Didier Trosset