Pages

Friday, December 15, 2017

Static variable behavior

How the static variable behaves?

#include
//int s1();
int s1()
{
  static int s;
  return s++;
}

main()
{
  int i=1;
  while (i<=2)
  {      
    i++;
    printf("S=%d\n", s1());
  }

}



Simple program. But here's the trick.
s is a static variable. 

    return s++;
the post increment is done as if:
    
    return s;
    s = s + 1;

So, when the first time s1() prints, it prints the value of s = 0, s being a static variable it's initialized to 0. But the first time s1() returns before it's being incremented. The next statement of course executes, and s is incremented. Since it's a static variable, it's not in the call stack, hence it's got incremented after the s1() function returns, but before the function actually exits.

As per Wikipedia:
When the program (executable or library) is loaded into memorystatic variables are stored in the data segment of the program's address space (if initialized), or the BSS segment (if uninitialized), and are stored in corresponding sections of object files prior to loading.

As per this 1995 Linux Journal article: http://www.linuxjournal.com/article/1059
Executable code is always placed in a section known as .text; all data variables initialized by the user are placed in a section known as .data; and uninitialized data is placed in a section known as .bss.

Hence the static variable actually increments.

No comments: