Harikesh
Harikesh

Reputation: 353

Memory and Scope of variable in c

Hi can anyone tell me would variable a remain in memory or would it get destroyed immediately.

#include <stdio.h> 

int main()
{
    {
        int a=1;
        lab:
        printf("Value of a : %d",a);  
    }   

    return 0;
}

would int a still remain in memory or not ?

Upvotes: 0

Views: 182

Answers (3)

Amin Negm-Awad
Amin Negm-Awad

Reputation: 16660

First of all: It is not implementation specific. The C standard explicitly says, that leaving a block destroys an object with auto (local declared) lifetime:

For such an object that does not have a variable length array type, its lifetime extends from entry into the block with which it is associated until execution of that block ends in any way. [ISO/IEC9899:TC3, 6.2.4, 5]

Of course, this is hard to test, because it loses it scope, too, in this case. (The other way around is easy to test.) But this is important for a formal reason: If you have a pointer to that object, which lives longer than the object, the program is always incorrect and the behavior is undefined – even an implementation let the object being alive. (Undefnied behavior includes that everything works fine.)

Upvotes: 1

Nobilis
Nobilis

Reputation: 7448

Nope, a has local scope (declared between brackets) so at the closing brace it will be cleaned up.

If you want it to persist for the entirety of the program, either declare it as static or put it outside of any braces, preferably before you use it.

This has the added benefit of having the compiler initialise it for you.

You can try out the following:

#include <stdio.h>
int a;

int main()
{
    static int b;

    int c;

    printf("%d, %d, %d\n", a, b, c); /* a and b should print 0, printing c is undefined behaviour, anything could be there */

    return 0;
}

As Bathsheba pointed out, static variables should be used judiciously if used in a multi-threaded environment.

Upvotes: 3

Bathsheba
Bathsheba

Reputation: 234715

a is destroyed (popped from the stack) when you get to the } following the line with printf , so no, it does not remain in memory at your comment line.

Upvotes: 3

Related Questions