Memory usage of global versus local variables

cglobals

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?

Best Answer

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.