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
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.
- 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.
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)