ThePatcher
ThePatcher

Reputation: 35

C simple static variable behaviour mystery

I am learning C right now and have a problem understanding something about the behaviour of a program with a static variable. As far as i know, static simply increases the scope of a variable to the file containing it.

   #include <stdio.h>
   int sum (int num) {
       static int sum =0;
       sum=sum+num;
       return sum;
   }

   int main() {
       printf("%d ",sum(55));
       printf("%d ",sum(45));
       printf("%d ",sum(50));
       return 0;
   }

if i execute this i get 55 100 150 as an output. And that's totally fine and expected. Then i thought could decraese one line by changing it a little bit like this:

int sum (int num) {
       static int sum =0+num;
       return sum;
   }

but this returns 55 55 55 I don't understand why it only returns 55 and doesn't add the other variables, that i am giving in the main to it.

Upvotes: 1

Views: 186

Answers (2)

anotherOne
anotherOne

Reputation: 1641

By default C variables exist only within the block where they are declared. They are said to be of automatic storage class.

By using the keyword static you are able to declare a variable of static storage class, i.e. a variable that exist for all the duration of the program.

Even though static variables exist during the whole program execution, they can be accessed only within the block in which they are declared.

Scope and storage class are two different things.

Upvotes: 1

August Karlstrom
August Karlstrom

Reputation: 11377

When you declare a static variable inside a function instead of outside a function it can only be accessed inside the function. Otherwise it works like a global variable in the sense that it exists throughout the lifetime of the program. Its initial value is determined when the program is compiled so it must be initialized with a constant expression. Any decent compiler should warn you if the initializer is not constant as in your example:

$ gcc -o test -Wall test.c
test.c: In function ‘sum’:
test.c:3:24: error: initializer element is not constant
        static int sum =0+num;
                        ^

Note that you should always compile your C programs with warnings enabled.

Upvotes: 2

Related Questions