c programming

Here is a simple c code.

int main()
{

static int i = 5;
if (--i)
 {
    printf("%d ", i);
    main(10);
}

}

The output of above code is 4 3 2 1.

my question is that why the code is not going in indefinite loop as main(10) function is called again in if condition.someone please explain this…thanks in advance.

The reason is :

A static variable inside a function keeps its value between invocations.

This means, local variables defined as static do not lose their value between function calls. In other words they are global variables, but scoped to the local function they are defined in.

So if you change static int to normal ( auto ) int like below


int main(){
//static int i = 5;
int i = 5;
if (--i)
{
    printf("%d ", i);
    main(10);
	}
}

The output will be : 4 4 4 4 4 4 4 … ( infinite number of 4’s, i.e., it will go into infinite loop as you thought it would)

Quote from Wikipedia:

In the C programming language, static is used with global variables and functions to set their scope to the containing file. In local variables, static is used to store the variable in the statically allocated memory instead of the automatically allocated memory. While the language does not dictate the implementation of either type of memory, statically allocated memory is typically reserved in data segment of the program at compile time, while the automatically allocated memory is normally implemented as a transient call stack.

See here and here for more details.

2 Likes