Scope VS Life of Variable in C

Scope vs life of variable in C

Scope is the region where the variable is accessible.

Life time is the time span during which an object remains valid.

An simple example:

#include <iostream.h>

void doSomething()
{
x = 5; //Error! Not Accessible
}

int main()
{

int x = 4;
std::cout<< x << endl;
{
int x = 2;
cout << x << endl;
}
doSomething();
std::cout<< x << endl;
return 0;
}

The above gives the output:

4

2

4

In above program,

lifetime of variable x = 4 is throughout the main, i.e: It remains alive throughout the execution of the main, Also it is accessible within the main, that is its scope. Note that it is not accessible in the function because it is beyond the scope of the variable x.

while scope and lifetime of variable x = 2 is within the enclsing braces{ } inside the main.

Scope vs. Lifetime of Variable

What is Scope?

Scope is the region or section of code where a variable can be accessed.

What is a lifetime?

Lifetime is the time duration where an object/variable is in a valid state.

For, Automatic/Local non-static variables Lifetime is limited to their Scope.

In other words, automatic variables are automagically destroyed once the scope({,}) in which they are created ends. Hence the name automatic to begin with.

What is wrong in your code example?

So Yes your code has an Undefined Behavior.

In your example scope of *p is entire function body after it was created.

However, x is a non-static local/automatic variable and hence the lifetime of x ends with it's scope i.e the closing brace of } in which it was created, once the scope ends x does not exist. *p points to something that doesn't exist anymore.

Note that technically x does not exist beyond its scope however it might happen that the compiler did not remove the contents of x and one might be able to access contents of x beyond its scope through a pointer(as you do).However, a code which does this is not a valid C++ code. It is a code which invokes Undefined Behaviour. Which means anything can happen(you might even see value of x being intact) and one should not expect observable behaviors from such a code.

scope or lifetime of variable in C

its basically a function activation record,which will be pushed on the system stack and when your function is returning it will first copy all values to the return result area,that is nothing but a=foo(); and then it will destroy that function activation record from the system stack,I hope it would help

Scope and lifetime of local variables in C

As you already know that b goes out of scope in each instance, and accessing that memory is illegal, I am only dumping my thoughts on why only one case throws the warning and other doesn't.

In the second case, you're returning the address of a variable stored on Stack memory. Thus, the compiler detects the issue and warns you about it.

The first case, however skips the compiler checking because the compiler sees that a valid initialized address is assigned to a. The compilers depends in many cases on the intellect of the coder.

Similar examples for depicting your first case could be,

char temp[3] ;
strcpy( temp, "abc" ) ;

The compiler sees that the temp have a memory space but it depends on the coder intellect on how many chars, they are going to copy in that memory region.

Confusion in Scope and Life Time of a local variable in c/c++

Scope refers to the the availability of an identifier.

Life time refers to the actual duration an object is alive and accessible legally during the execution of the program. They are distinct things.

Your code has undefined behaviour because the lifetime of the object n is over at the closing } because you access it through a pointer.

A simple example might make it clearer:

#include<stdio.h>
int *func()
{
static int var = 42;
return &r;
}

int main(void)
{
int *p = func();
*p = 75; // This is valid.
}

Here, var is has static storage duration. i.e. it's alive until the program termination. However, the scope of the variable var is limited to the function func(). But var can be accessed even outside func() through a pointer. This is perfectly valid.

Compare this to your program. n has automatic storage duration and its lifetime and scope both are limited to the enclosing brackets { }. So it's invalid to access n using a pointer.

However, if you make change its (n) storage class to static then you can do what you do as the object is alive even outside enclosing brackets.

Life cycle of a variable

When you ask questions like this, you should be clear whether you are asking about C semantics or about program implementation.

C semantics are described using a model of an abstract computer in which all operations are performed as the C standard describes them. When a compiler compiles a program, it can change how the program is implemented as long as it gets the same results. (The results that must be correct are the observable behavior of the program: its output, including data written to files, its input/output interactions, and its accesses to volatile objects.)

In the abstract computer, memory for x is reserved from the time an execution of foo starts until that execution of foo ends.1, 2

So, in the abstract computer, it does not matter if x is used or not; memory is reserved for it until foo returns or its execution is ended in some other way (such as a longjmp or program termination).

When the compiler implements this program, it is allowed optimize away x completely (if it and its address are not used in any way that requires the memory to be reserved) or to use the same memory for x that it uses for other things, as long as the uses do not conflict in ways that change the observable behavior. For example, if we have this code:

int x;
int *y = &x;
x = 3;
printf("%d\n", x);
int b = 4;
printf("%d\n", b);

then the compiler may use the same memory for b that it uses for x.

On the other hand, if we have this code:

int x;
int *y = x;
printf("%p\n", (void *) y);
int b = 4;
printf("%p\n", (void *) &b);

then the program must print different values for the two printf statements. This is because different objects that both exist at the same moment in the abstract computer model must have different addresses. The abstract computer would print different addresses for these, so the compiler must generate a program that is faithful to that model.

Footnotes

1 There can be multiple executions of a function live at one time, due to nested function calls.

2 Sometimes people say the lifetime of x is the scope of the function, but this is incorrect. The function could call another routine and pass it y, which has the address of x. Then the other routine can access x using this address. The memory is still reserved for x even though it is not in the scope of the other routine’s source code. During the subroutine call, the execution of foo is temporarily suspended, but it is not ended, so the lifetime of x has not ended.

The scope and lifetime of static local variable in c++

Scope is limited means any attempt to access x directly outside the scope is forbidden.

Within a scope, unqualified name lookup can be used to associate the
name with its declaration.

But you can always return a pointer or reference to this variable if variable is alive and you change it through that reference or pointer which points to the same variable. The name of this reference may be anonymous (temporary) or may be bound to some named reference.

About lifetime, it starts when the function containing static variable is called first time and ends when the program end.



Related Topics



Leave a reply



Submit