_
#include<stdio.h>
int main()
{
int a=5,b=10;
printf("%d %d");
return 0;
}
_
#include<stdio.h>
int main()
{
int a=5,b=10;
printf("%d %d");
return 0;
}
Undefined behavior: it will output two undefined numbers.
Sometimes it may print values stored in variables because of the way the stack works, but this is far from guaranteed.
A good compiler will issue a warning about this. The output is undefined, but in practice, since printf()
expects two extra arguments, it will grab the two integers from the place where it expects its arguments: the stack. For example, when I tried it with gcc, the output was
15224820 134513712
It will print two "random" values from the stack because you have improper arguments being passed to printf. You need to pass a and b as arguments.
Try this one:
#include<stdio.h>
void f(int x,int a,int b) {}
int main()
{
int a=5,b=10;
f(0,a,b);
printf("%d %d");
return 0;
}
Edit: Well, I compile it with gcc:
$ gcc hehe.c
hehe.c: In function ‘main’:
hehe.c:8: warning: too few arguments for format
$ ./a.out
5 10$
It will as everybody said, output two undefined numbers. It is not though, as if the compiler invents two undefined arguments just to have something to print.
What undefined really means, is that the result will differ depending on how the compiler is implemented, and the compiler may do whatever it wants in this situation, even abort execution.
The reason though, you see the numbers 5 and 10 being output when you compile this in TC, is that the way TC works, is that the numbers 5 and 10 are pushed on the stack by the initialization of a
and b
variables right before the printf call.
a
and b
are both on the stack and
printf()
, in turn works by reading what is on the stack as arguments.
Try for instance with static
variables instead of auto variables, like so:
#include<stdio.h>
int main()
{
static int a=5,b=10;
printf("%d %d");
return 0;
}
static
variables are not put on the stack, and hence, when you call printf()
there will be something entirely different on the stack, like function return addresses or the arguments to main()
or something else entirely. The output will then not be 5 and 10, but something else. Try it!
(TC is actually a very interesting compiler to learn C in, because it is pretty simple in how it works. The output of modern compilers and calling conventions often are more difficult to follow.)