I took a C Advanced Course on Udemy, and there is a question from there: What will be the output of the following code?
#include <stdio.h>
int main(void){
static int i=5;
if(--i){
main();
printf("%d ", i);
}
}
The right answer is 4 3 2 1
, but when I run this code in my IDE (and online compilers), it prints 0 0 0 0
.
In the course lector uses cygwin compiler and I have g . May it be the reason of the inconsistency?
Also I'm wondering if if(--i)
method is faster then for
loop by the concept of performance?
Thank you.
CodePudding user response:
The posted code shall print 0 0 0 0
because the printf
is after the recursive call, i.e.
main(); // Recursive call
printf("%d ", i); // Print after
If you instead do:
printf("%d ", i); // Print before
main(); // Recursive call
the output will be 4 3 2 1
So I think your lector used the last form and you used the first form, i.e. different code, different results
CodePudding user response:
The reason is main()
is called before printf("%d ", i)
. So when if block is executed, main()
function is called before printing the value of i
and it's continue to do so until if-condition
is false. Here if-condition
became false when i
is equal to 0
. When the if-contidion
is false the function return to the previous state from where it have been called and then print the value of i
, which is now 0
.
To print 4 3 2 1
, print the values before calling main()
funtion like bellow
int main(void){
static int i=5;
if(--i){
printf("%d ", i);
main();
}
}