Home > Net >  Why static in C gives two different values. At first 5, then 1 after calling the function?
Why static in C gives two different values. At first 5, then 1 after calling the function?

Time:05-10

The following code of static keyword gives two different output before and after calling a function

#include<stdio.h>
static int count=5;
int fun()
{
    count = 0;
    count  ;
    return count;
}
int main()
{
    printf("%d ", count);
    
    printf("%d ", fun());
    printf("%d ", fun());
    printf("%d ", count);
    return 0;
}

OUTPUT: 5 1 1 1

Q) Why is count giving two different values; at first it's 5 then it is 1 after calling the function?

CodePudding user response:

This

int fun()
{
count = 0;
count  ;
return count;
}

is the same as

int fun()
{
    count = 1;
    return count;
}

The function assigns 1 to the global count and then returns its value.

This

static int count=5;

initializes the global count with the value 5.

Hence, before calling fun the value of count is 5. After calling fun the value of count is 1. fun always returns 1, it does not matter how often you call it. And after calling the function the global count has the value 1.

static is irrelevant here. The code prints the same when count is not declared as static.

CodePudding user response:

WHY COUNT IS GIVING TWO DIFFERENT VALUES AT FIRST 5 THEN AT LAST 1

Because you're calling a function named fun that:

a) first reset the count to 0

b) then increment that count.

Thus every time you call the function fun the count is reset to 0 and then incremented to 1 and which is returned by the function.

  • Related