Here and Here I found that variables in block are created when execution reaches that block,
To prove that I tried this:
int main()
{
{
char a;
printf("Address of a %d \n",&a);
}
char b;
printf("Address of b %d \n",&b);
}
As expected b was created first (because outer block is executed sooner than inner), and when the execution reached inner block a was created. Output of the above code:
Address of a 2686766
Address of b 2686767
(Tested on x86 (stack grows downwards, so variable with greater address was created first)).
But what about this one?:
int main()
{
{
char a;
printf("Address of a %d \n",&a);
} // I expected that variable a should be destroyed here
{
char b;
printf("Address of b %d \n",&b);
}
}
Output:
Address of a 2686767
Address of b 2686766
I expected that a was destroyed at closing brace of the first block statement, so address where a was located is now top of stack, and b should be created here, thus in the Output above both addresses should be equal, but they aren't? Are variables destroyed at the end of block? If not, why?
The lifetime of a variable or object is the time period in which the variable/object has valid memory. Lifetime is also called "allocation method" or "storage duration."
2. The lifetime of a variable is the period throughout which the variable exits in the memory of your Python program. The lifetime of variables inside a function is as long as the function executes. These local variables are destroyed as soon as the function returns or terminates.
A variable which is declared inside a class, outside all the blocks and is marked static is known as a class variable. The general scope of a class variable is throughout the class and the lifetime of a class variable is until the end of the program or as long as the class is loaded in memory.
The lifetime of a variable defines the duration for which the computer allocates memory for it (the duration between allocation and deallocation of memory). In C language, a variable can have automatic, static or dynamic lifetime. Automatic − A variable with automatic lifetime are created.
There are no rules for how the compiler places variables in memory. It could very well reserve space for both of them at the same time, if that is "easier" in some way.
It is allowed to reuse the space for variables in different scopes, but not required. Saving a single byte might not be worth the trouble of trying to "optimize" the allocation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With