Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursion and static variables [duplicate]

Tags:

c

recursion

So I was preparing for an entrance exam here in India when I came across this piece of C code

#include <stdio.h>
int main(void) {
    static int i = 4;
    if (--i) {
        main();
        printf("%d", i);
    }
}

I thought the printf statement never gets executed and the output will be blank. But I saw the answer to be 0000 and that this happens due to the static keyword with the int.

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

like image 977
Sriram R Avatar asked Aug 01 '17 19:08

Sriram R


People also ask

Can static variable be used in recursion?

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.

Why recursive functions are static?

When applied to an object within a function, static means that the variable exists beyond the duration of the function. In the context of a recursive function, it also means that there is only one copy of the variable for all recursion levels rather than one per recursion level, which is usually what's needed.

Can static variables be declared twice?

Yes it is. Each of your b variables is private to the function in which they are declared. Show activity on this post. b in func and b in main are two different variables, they are not related, and their scope is inside each function that they are in.

How many possible copies can a static have?

Static Members Only one copy of a static member exists, regardless of how many instances of the class are created.


2 Answers

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.

like image 68
Corvus Crypto Avatar answered Sep 28 '22 11:09

Corvus Crypto


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

like image 24
AndyG Avatar answered Sep 28 '22 11:09

AndyG