InterviewSolution
Saved Bookmarks
| 1. |
What is the difference between global int and static int declaration? |
|
Answer» The difference between this is in scope. A truly global variable has a global scope and is visible everywhere in your program. #include <stdio.h> int my_global_var = 0; int main(void) { printf("%d\n", my_global_var); return 0; }global_temp is a global variable that is visible to everything in your program, although to make it visible in other modules, you'd need an ”extern int global_temp; ” in other source files if you have a multi-file project. A static variable has a LOCAL scope but its variables are not ALLOCATED in the stack segment of the memory. It can have less than global scope, although - like global variables - it RESIDES in the .bss segment of your COMPILED binary. #include <stdio.h> int myfunc(int val) { static int my_static_var = 0; my_static_var += val; return my_static_var; } int main(void) { int myval; myval = myfunc(1); printf("first call %d\n", myval); myval = myfunc(10); printf("SECOND call %d\n", myval); return 0; } |
|