Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How the static variable gets retrieved for every function call

Tags:

c

function

static

We know that when the control exits from function the stack space will be freed. So what happens for static variables. Will they be saved in any memory and retrieved when the function gets called ??

like image 281
seereddi sekhar Avatar asked Apr 21 '26 07:04

seereddi sekhar


2 Answers

The wiki says:

In the C programming language, static is used with global variables and functions to set their scope to the containing file. In local variables, static is used to store the variable in the statically allocated memory instead of the automatically allocated memory. While the language does not dictate the implementation of either type of memory, statically allocated memory is typically reserved in data segment of the program at compile time, while the automatically allocated memory is normally implemented as a transient call stack.

and

Static local variables: variables declared as static inside a function are statically allocated while having the same scope as automatic local variables. Hence whatever values the function puts into its static local variables during one call will still be present when the function is called again.

like image 135
Rahul Tripathi Avatar answered Apr 23 '26 20:04

Rahul Tripathi


Yes, static variables persist between function calls. They reside in data section of the program, like global variables.

You can (and probably should) read more about general memory layout of C applications here.

like image 44
kaspersky Avatar answered Apr 23 '26 21:04

kaspersky



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!