Memory and Scope of variable in c -


hi can tell me variable remain in memory or destroyed immediately.

#include <stdio.h>   int main() {     {         int a=1;         lab:         printf("value of : %d",a);       }         return 0; } 

would int still remain in memory or not ?

nope, a has local scope (declared between brackets) @ closing brace cleaned up.

if want persist entirety of program, either declare static or put outside of braces, preferably before use it.

this has added benefit of having compiler initialise you.

you can try out following:

#include <stdio.h> int a;  int main() {     static int b;      int c;      printf("%d, %d, %d\n", a, b, c); /* , b should print 0, printing c undefined behaviour, there */      return 0; } 

as bathsheba pointed out, static variables should used judiciously if used in multi-threaded environment.


Comments