0

Here's a code written in c

#include<stdio.h>

int foo()
{
    static int a=0;
    a=a+1;
    return a;
}

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

I've compiled this code using gcc11 in eclipse IDE and I've got 3 as my output.

Here's what I think should happen which leads me to the output as 1 not 3.

Function call-1: The main function calls the function foo and the control goes to the function foo then the variable 'a' in foo is created with an initial value of zero then it is incremented by one and this incremented value (1) is returned to the main function. At this step the variables created for the function foo should have been destroyed.

Function call-2: Same as Function call-1:

Function call-3: Same as Function call-1:

In the end the value printed by the printf function in main should have been 1.

Why the output of the program is 3?

Keshaw Kumar
  • 317
  • 1
  • 4
  • 15

4 Answers4

3

static variables are not destroyed when the function returns. Remove that keyword and it will work as you expected.

Edit: The static variable is only present in the scope of its own function. You can create other variables with the same name (static or otherwise) in other functions.

void foo()
{
  static int a = 0;
  a++;
  printf("%d\n", a);
}

void bar()
{
  int a = 10;
  a++;
  printf("%d\n", a);
}

void baz()
{
  static int a = 100;
  a++;
  printf("%d\n", a);
}

int main()
{
  foo();
  bar();
  baz();

  foo();
  bar();
  baz();
  return 0
}

This will print:

1
11
101
2
11
102
rohit89
  • 5,745
  • 2
  • 25
  • 42
3

Try this with more printing.

#include<stdio.h>

int foo()
{
    static int a=0;
    a=a+1;
    printf("a is now: %d",a);
    return a;
}

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

You will notice that the variable a is initialised just the once and its value is retained across function call invocations.

See here: http://en.wikipedia.org/wiki/Static_variable

Angus Comber
  • 9,316
  • 14
  • 59
  • 107
1

Here, the variable a is a Static Variable.
Although the scope of variable has to be ended after the complete execution of function. But the Static variable has Scope through out the program and they are not deleted throughout the program.

if it was

int a;

in the place of

static int a;

The result would have been different.

Asis
  • 683
  • 3
  • 23
1
  • Static variable inside a function keeps its value between invocations.

see the below example for difference between static and normal variable.

void sample()
{
    int nv = 10;//nv refers normal variable.
    static int sv  = 10;//sv refers static variable.
    nv += 5;
    sv += 5;
    printf("nv = %d, sv = %d\n", nv, sv);
}
int main()
{
    int i;
    for (i = 0; i < 5; ++i)
    sample();
}

output:

nv = 15, sv = 15
nv = 15, sv = 20
nv = 15, sv = 25
nv = 15, sv = 30
nv = 15, sv = 35
Dharma
  • 3,007
  • 3
  • 23
  • 38