FAQ Style Article

Static variables in C

This article explains static variable properties using tricky programs

Default value of static variables – What is it?
Zero (0)

Life of static local variable – Is it preserved across calls?
Yes, static variables are initialized once. Local static variables preserve value across function calls.

Sample tricky program with output
#include <stdio.h>

int foo()
static int bar;
return bar;

int main()
printf("%d ", foo());
printf("%d ", foo());

1 2

Static local variable bar is initialized to 0 at the start of the program.
In the first call to foo, initial value of bar is 0, so value returned after incrementing is 1.
In the second call to foo, bar retains previous value of 1, hence value returned after incrementing bar is 2.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: