static vs ordinary variables

Is it more expensive to use too many static variables instead of ordinary variables? If yes, then how?------------This is a topic given to me to find out about and I don't even know what are static variable except that they live throughout the life of program

and only disadvantage of using static variable instead ordinary variables in my mind is just they will use memory even when we don't need them

Is there anything else too???
Yes, like in a for-loop:
1
2
3
4
5
for (;;) {
    static int i = 0;
    //...
    i++;
}

i will keep its value instead of being set to zero each loop.

Is it more expensive to use too many static variables instead of ordinary variables?

I don't know...
I'd believe that it would be more expensive to use static variables instead ordinary variables due to the fact that automatic variables are created and destroyed when they go in and out of scope (so memory is freed after the program is out of the block in which a variable is declared). Whereas static variables are stored until the program terminates - meaning they remain allocated even if you don't need them in your program after a certain point; which is "wasted" memory.

Edit: Pretty much what OP said.
Last edited on
thanks, and is there anything more to be known about static or automatic variables??? I guess there must be.
- static variables are not thread safe. If the same function is being called from multiple threads, both threads are using the same var if it's static, but are using two different vars if non-static.


- static variables are not re-initialized like normal vars are. IE, in programmerdog's example, 'i' will only be set to zero for the first iteration of the first time that for loop is executed. This might be intentional, but might be an unwanted side-effect.
I get it, static variables are not re-initialized but are automatic variables re-initialized ???
Well they are destroyed when they leave scope so a brand new one is added to the stack which makes them get re-initialized. (If you are talking about programmerdog's example with a non-static variable)
Last edited on
got it, thanks all O' ya
Topic archived. No new replies allowed.