somenath wrote:
Hi All,
Please help me to understand the reason behind the output of the
following program
What is the output of the following program:
The output -- in fact, the entire behavior of the
program -- is undefined, because the program calls the
printf() function without a correct declaration in scope.
Even if you get away with that error, there may be no
output at all because the program does not generate a
complete line ending with a '\n' character. And even if
it generates output, the host environment may do something
nasty with it when the program exits without supplying a
valid exit status. In what follows, I'll assume the
indicated corrections have been made:
#include <stdio.h /* so printf() will be declared */
int i=10;
int f1()
{
static int i = 15;
printf("f1:%d ", i);
return i--;
}
main()
int main(void)
{
int i, j;
i = 5;
printf("%d %d %d", f1(), f1(), i);
printf("%d %d %d\n", f1(), f1(), i); /* ending the line */
return 0; /* valid exit status */
}
OUTPUT is
f1:15 f1:14 14 15 5
Either the undefined behavior has caught up with you,
or the C implementation you use is hopelessly broken, or
you have made an inaccurate report. The "output" you show
has fewer space characters than your printf() formats should
produce.
Now, why am I making such a fuss over a little bit of
white space? Because it indicates that you almost certainly
typed the so-called "output" free-hand, and did not cut and
paste or otherwise make a perfect copy of the actual output.
This in turn casts doubt on the accuracy of your transcription
of the program source: How many differences are there between
what you've showed us and what you actually ran? I can only
guess -- and if I guess wrong, it's *your* fault.
In the future, make *exact* copies of code, output, error
messages, and whatever else you're asking about. Otherwise,
the answers you get may have little to do with the problem
you face.
The two possible outputs of the (corrected) program are
f1:15 f1:14 15 14 5
f1:15 f1:14 14 15 5
.... depending on the order in which the printf() inside main()
evaluates its arguments. C does not specify that order, so
different implementations may do it differently: left-to-right,
right-to-left, or even more peculiar orderings are possible.
In your case, it appears that the arguments may have been
evaluated right-to-left.
How is it possible ? Is it not be f1:15 f1:14 14 13 5
No: That output is not possible (even allowing for the
changes in white space, and assuming a corrected program).
Perhaps you misunderstand how `--i' and `i--' are different;
a session with your textbook may be helpful.
--
Eric Sosman
es*****@acm-dot-org.invalid