What is a static property in Objective C.

9.8 Static Variables

Before I explain the static variables to you, you should first have a look at the following program example:

/ * func7.c * / #include void increment (void) {int i = 1; printf ("value of i:% d \ n", i); i ++; } int main (void) {increment (); increment (); increment (); return 0; }

When you run the program, it prints the "value of i: 1" three times. However, one must assume here that the programmer had other intentions, since he is incrementing the value of the variable i at the end of the function. The fact that this does not work has to do with the memory management of the stack. More on this topic can be found in Section 9.20.1, »Excursus: Stack«.

You can now write the keyword static in front of the variable in this program. So change this function:

void increment (void) {static int i = 1; printf ("value of i:% d \ n", i); i ++; }

This means that the values ​​1, 2 and 3 are actually output for the variable i. You owe this to the keyword static. This is because static variables do not lose their value when their frame of reference is terminated (i.e. when the function is terminated), but instead retain their value. That this succeeds is due to the fact that static variables are not stored in the stack segment of the CPU, but in the data segment. But be careful: Static variables must be initialized when they are declared!

your opinion

How did you like the Openbook? We always look forward to your feedback. Please send us your feedback as an e-mail to [email protected]