Recursion and static variables [duplicate] Recursion and static variables [duplicate] c c

Recursion and static variables [duplicate]


In the context of the question being about recursion, it will print out "000" (I don't know why the answer shows 4 zeros because with '--i' decrement happens before assignment). If you unroll the calls you get:

if (--i) { //i == 3    if (--i) { //i == 2        if (--i) { //i == 1            if (--i) { //i == 0                // rest does not get evaluated since the condition is false            }            printf("%d", i); // i is 0 now        }        printf("%d", i); //i is still 0    }    printf("%d", i); //i is still 0}

However like most have mentioned this code sucks and I would advise you never consider this level of sloppiness for any software you write.


It is legal to recurse on main in C* (although why would you?)

Additionally, C11 (5.1.2.2.1) states:

It shall be defined with a return type of int ... [or] If the return type is not compatible with int, the termination status returned to the host environment is unspecified.

(C++ states that the return type must be int)

So this portion of the code is actually standard-compliant, but the actual return is implementation-defined (thanks @chux)

Can anyone explain why the printf executes or is that guy wrong?

If you're compiling C with a C++ compiler, guy is wrong. Otherwise the code will compile.

Now that this is out of the way, the printf will indeed execute because the static variable is only ever initialized once, as per 6.2.4/3

An object whose identifier is declared [...]with the storage-class specifier static has static storage duration. Its lifetime is the entire execution of the program and its stored value is initialized only once, prior to program startup

*It is definitely NOT legal in C++. From [basic.start.main]: "The function main shall not be used within a program". There's a lot of C++ asides in this answer because the question was originally tagged as C++ and the information is useful


Can anyone explain why the printf executes or is that guy wrong?

Because main returns.

This answer writes out the logic, but I see that you are still asking this in comments. So I'm going to say the same thing in a different way and hope that it is clearer to you.

Because the variable is static, prior to the first call, the variable is declared and set to 4. Because it is static, the same variable will be used every time. It just skips over the declaration and initialization if called again (or likely even the first time, as static variables can be allocated before running).

In the first call, the variable is decremented to 3. 3 is a truthy value, so we do the block of the if. This calls main recursively.

In this second call, the variable is decremented to 2. 2 is still truthy in C. We call main recursively again.

In this third call, the variable is decremented to 1. 1 is still truthy. We recurse to main again.

In this fourth call, the variable is decremented to 0. 0 is falsey in C. We do not enter the block of the if. We do not recurse. We do not print. There's nothing left to do in this call to main. It returns at the end.

Now we're back in the third call. We just returned from the call to main. We are still inside the if block. The next statement is a printf. The value of the variable is now 0. So we print a 0. Nothing left to do, we return at the end.

Now we're back in the second call. Still 0, so we print another 0 and return.

Now we're back in the first call. Still 0, so we print another 0 and return.

We printed 0 three times, so 000

As you note, on the way down, we don't print. We print on the way back up. By that time, the variable is 0. And we enter the then block of the if three times. So we recurse and then print three times.

When you call a function recursively, you don't eliminate the previous call. You put it on the stack. When done, you come back to the place where you left and continue with the next statement.

You may want to think about how the following three pieces of code will react differently:

void recurse() {    static int i = 4;    if (--i) {        recurse();        printf("%d", i);    }}

Prints 000 when called the first time. Does nothing thereafter.

void recurse(int i) {    if (--i) {        recurse(i);        printf("%d", i);    }}

Will print 123 if called as recurse(4). As a parameter, we are dealing with a different i each time the function is called.

void recurse(int i) {    if (--i) {        printf("%d", i);        recurse(i);    }}

Prints 321 if called as recurse(4). Printing on the way down rather than when coming back up.

void recurse(int i) {    printf("%d", i);    if (--i) {        recurse(i);    }}

Prints 4321 if called as recurse(4). It prints on the way down, rather than the way up.

void recurse() {    static int i = 4;    printf("%d", i);    if (--i) {        recurse();    }}

Will print 4321. We're printing on the way down, not the way up. Note how the parameter and the static variable give the same result this way. However, if this is called a second time, it will do nothing. The parameter would print the same thing again.

void recurse() {    int i = 4;    if (--i) {        recurse();        printf("%d", i);    }}

Loops forever. Without the static we make a new i each time. This will run until it overloads the stack and crashes. No output because it never makes it to the printf.

The easiest way to check this is to go somewhere like ideone.com and run the code. Asking why it prints something is reasonable for this site. But asking what it prints is something that you should answer yourself.