2

I am a beginner in C coding. I'm writing a C code where a variable is required to be used by different functions. I want to ask whether to use a global variable and manipulate it through functions or declare it as local variable and pass from function to function as argument.

My understanding is that if I declare it as global variable, same memory space will be used by different functions whereas if I use it as local, more memory will be used as it will be defined and declared every time the function is called. Is this true?

3

First off, "defining" and "declaring" are things you do in source code, rather than at runtime. Some variable declarations and definitions correspond to actual machine code that gets executed, and some do not. As far as I know, the definition of an additional function parameter or local variable will not generate any additional machine code, but will merely change how many bytes the CPU's frame/stack/etc pointers get moved as part of the function call.

What is true is that memory for a function parameter gets allocated on the stack every time you call that function (by the aforementioned pointers being moved), while memory for a global variable only gets allocated once. In that sense you're absolutely right. But the memory allocated by those function calls will also be immediately deallocated when the function exits, while the global variable's memory has to stick around for the entire length of the program. In that sense "more memory will be used" is not really correct.

Of course, this would be a very silly reason to use a global variable, because any change in memory usage or runtime performance is likely to be extremely tiny or totally nonexistent, while adding global variables you don't need usually makes programs far more brittle and untestable in the long run (see Why is Global State so Evil? for more on that). Definitely do not do it unless you have hard data from profiling tools that shows the global variable "optimization" is actually a big performance win over the local variable.

  • 2
    Also, the stack is almost always in the cache, even if the function hasn't been called in a while. Global variables will only be in the cache if the global has been used recently. Further, some local variables live in CPU registers (for optimized code), and so occupy no memory at all and enjoy the fastest of accesses. It would be highly unusual for a global variable to be allocated to a CPU register. – Erik Eidt Apr 4 '16 at 14:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.