10th Dec 2017, 4:44 AM
Anurag Tripathi
Anurag Tripathi - avatar
3 Answers
+ 3
There is a recursive call to main, which will create "stacks" of the main function, which will then execute when the base condition is met, thus exiting the recursive loop. The integer variable 'var' needs to be static so that there will only be one shared variable between all the stacks, otherwise you would end up with a continued recursive call to main. Similar to an infinite loop. The recursive function would call main over and over until you reached a stack overflow and ran out of available memory space in your computer. This would crash the program and potentially the computer. This would occur because each call to main will create a new integer variable 'var' with an initial given value of 5. 'var' will only ever be decremented to 4 on each stack. Making 'var' static means that there will only be the one integer variable created and when the declaration line for var is reached again in each call to main on the stack it will essentially be ignored instead of creating a new integer variable or reassigning the value back to 5. Thus, each call to '--var' in the if condition will reduce the value of 'var' by one until 0 is reached, which would be considered the base case, as 0 is equivalent to false in C++ and any other non-zero number is evaluated to true. So, you may expect the output to be: 4 3 2 1 But instead it will be: 0 0 0 0 This is due to the value of 'var' being static and the output line exists after the recursive call to main. So, when it is output the value of 'var' is 0. Hopefully that's not to confusing. If you need further help understanding just ask for clarification on what you don't understand.
10th Dec 2017, 5:45 AM
ChaoticDawg
ChaoticDawg - avatar
+ 1
you get 0000 in the output due to main method call recursively and also due to static variable. static member does not reinitialise when the method calls again. static members are initialise only once when method called for the first time. for better understanding the static properties use below code. #include <stdio.h> //using namespace std; int main() { static int var = 5; if(--var){ printf("%d\n", var); main(); } return 0; }
10th Dec 2017, 5:42 AM
$Ā¢šŽā‚¹š”­!šØš“
$Ā¢šŽā‚¹š”­!šØš“ - avatar
+ 1
Thank you so much
26th Dec 2017, 9:06 AM
Anurag Tripathi
Anurag Tripathi - avatar