Reputation: 15405
So in my c file I have a variable:
static int32_t currentAddress = 0x00000000;
I was wondering if I use currentAddress to set fields within say struct A as 0. Then say I increment currentAddress elsewhere, will the field within A also change?
Basically I don't understand what static does in this case and when to use it.
Upvotes: 0
Views: 485
Reputation: 9082
In case you mentioned, the valie is copied from currentAddress into the variable you are assigning to. So, changing currentAddress's value, will not change other values.
In C, static limits the variable's visibility to the current translation unit (in simpler terms, in the current source file, if the project has multiple source files). Also, it does not destroy variables at exiting from their scope, as it would happen with non-static variables. For example:
int foo(){
int a = 0;
a++;
return a;
}
int bar(){
static int a = 0;
a++;
return a;
}
Every call to foo() returns 1, because variable a is created, incremented, returned and destroyed. But, every call to bar() increases the value returned (it returns 1 first time, then 2, 3, 4, and so on), because the a variable is not destroyed anymore. Also note that the variable accessing rules are preserved: the a from bar cannot be accessed outside the bar function.
Upvotes: 1
Reputation: 7973
The field within A will get the current value of currentAddress, which is 0. Changing currentAddress later won't affect the field of A unless you assign the field with currentAddress again, at which point the field of A will have the new value of currentAddress.
The static
declarator sets the scope and lifetime of the variable currentAddress. You haven'r specified whether currentAddress is in file scope or inside a function. Either way, the variable will retain its value unless you modify it.
Upvotes: 2