top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

C: Is there any difference between local variable and automatic variable?

0 votes
954 views
C: Is there any difference between local variable and automatic variable?
posted May 22, 2017 by anonymous

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

+1 vote

a local variable can be auto or other type as the storage class.
There are 2 things that you need to understand with variable
1) Scope (how far its accessible)
2) lifetime (how long its available)

For example, a local variable can be auto variable, in which case its memory is allocated from the stack and has a scope within the local block. If the local variable is specified as "static", then its allocated from data segment and though it has a local scope, the life time is till the program exits. if a local variable is declared as register, the compiler "tries" to allocate a memory from one of the CPU registers and its life time is only till the block.

The other type of variables are extern variable which is defined elsewhere / in another file.

The pointer variables, when declared local to a block:
the memory pointed to-by the pointer variable are allocated from heap.
the pointer variable itself is local.
This is why it is important to free the memory allocated to a pointer , because once you exit the block, the variable is lost, but chances are the memory pointed to by the variable is still marked for use.

ex:
int myfunc()
{
int a=10; //AUTO variable, scope is local to myfunc, allocated in stack when myfunc is loaded and deallocated when the function is unloaded
static int b =10; // static variable local to myfunc. allocated in data segment when my func is laoded and continues to be in mremry until the program exits
register int c =10; // register variable. compiler tries to allocate in CPU memory registers else, will be allocated from stack and scope is only till the myfunc() is in use.
int *ptr = (int *) malloc (sizeof(int) * 5); //5 integers - array of 5 ints //Now the memory for 5 integers are allocated from heap, but the variable ptr itself is allocated in stack which means when myfunc exits, ptr variable would be removed from memory. but to remove the 5 integers memory, we need to do free on ptr.
for (int I=0;i<5;i++)
ptr[I] = i;

}

answer May 22, 2017 by Narendran P
Similar Questions
+2 votes

I have a doubt regarding variable declaration inside a for loop.

My understanding is, the statements inside loop will be executed repeatedly till it exit from the loop.

My doubt:
if we declare a variable inside a for loop, will it be created every time the loop executes? or during the compilation process the local variable declaration and initialization will be moved to different section.

Example

    for(i=0;i<10;i++) {
            int j;
            ...
    }
...