Very few authors discuss the "printf", included in the stdio (please do not call it "studio") function in complete detail - its functionality, sequence of executing the arguments and so on... Here are a few questions to get you thinking:
1. In what order does printf accept and execute the arguments : printf ("A1 = %d, A2 = %d", int_arg1, int_arg2);
2. What does printf print in this case: printf ("Here = %d and There = %d");
Most of you would say "garbage". But what is that garbage and where does it come from?
Lemme see some accurate answers
What are the answers???
ReplyDelete1. In what order does printf accept and execute the arguments : printf ("A1 = %d, A2 = %d", int_arg1, int_arg2);
ReplyDeleteQuite obviously, the compiler encounters "printf" before the arguments. Hence it executes printf. Now it sees that printf has two arguments. It picks up the last argument in the list, viz int_arg2 first, followed by int_arg1. You can observe it by executing this statement:
printf ("\nprintf calling", f1 (), f2 () );
where
int f1 (void) { printf ("\nHere, in function f1" ); }
and
int f2 (void) { printf ("\nAnd now in function f2"); }
are simple functions to track the control flow.
The output would be...
printf calling (calling printf)
And now in function f2 (function f2 executes)
Here, in function f1 (function f1 executes)
2. What does printf print in this case: printf ("Here = %d and There = %d");
ReplyDeleteIt starts printing values from the TOS (top of stack).
consider the code snippet:
int i = 20;
int j = 25;
printf ("Here = %d and There = %d");
First, the value of i is pushed onto the stack followed by the value of j. Hence, the TOS holds the value of j after second push operation.
The printf statement has only a string constant as an argument. Also, printf expects two integer arguments due to the usage of format specifiers %d. Since no integer arguments are passed, printf picks up the value from TOS and prints it (in place of the first %d). It then increments the stack pointer and prints the next value in stack (in place of the second %d).
Hence the output is...
Here = 25 and There = 20