hello all, i came accross an aptitude question ..
int
main()
{
int a = 10, b = 20, c = 30;
printf("%d\t%d\t%d");
}
it gives output
30 20 10
what is the reason of such behaviour of printf().
thank you.
hello all, i came accross an aptitude question ..
int
main()
{
int a = 10, b = 20, c = 30;
printf("%d\t%d\t%d");
}
it gives output
30 20 10
what is the reason of such behaviour of printf().
thank you.
This is undefined behavior, it is probably caused by the fact that a, b, and c values are on the stack.
Undefined behavior means:
Basically: never do that kind of thing.
Let me tell you what I got in 4 different runs at my RHEL5 machine :
-1081779332 10 20
-1075902180 10 20
-1080081124 10 20
-1078653316 10 20
// And the code was -- almost same!!! :)
#include <stdio.h>
int
main()
{
int a = 10, b = 20, c = 30;
printf("\n %d\t%d\t%d\n");
}
The stack is the program's "blackboard". It's the place local variables and function call stack frames get stored, so anything that does anything in your program is going to leave junk scribbled all over it. Make a few function calls and printf's output may change... Calling printf without giving it any arguments to print just causes it to read the "top" of it no matter what's on it. Which bits? That's undefined -- but can include local variables and function call frames. Really, your output is not so amazing.
Thank you all for your reply. Thanks.
I think the way the variables are declared could have influence on what you get.
like:
int a, b, c
is different from
int a;
int b;
-----
here you store all variables sequencially on the stack, so there'd be high probability that printf return these recently stored variables
There is no difference in the two ways and has no effect at all on the address location each variables get. They all are created on the stack only.
Just print the address and notice the same. Also for your better understanding you may look the segregation of the process memory layout at /proc/<pid>/mmap and map their addresses printed.
In most library implementations, printf is simply a wrapper around another another version of printf which takes a va_list as an argument. No checking is done on the variable arguments "..."
For example, here is what AT&T's AST libast does:
int
printf(const char* fmt, ...)
{
va_list args;
int v;
va_start(args, fmt);
v = sfvprintf(sfstdout, fmt, args);
va_end(args);
return v;
}
This is why you get the observed behavior.