0 votes
in C Plus Plus by
What is the difference between global int and static int declaration?

1 Answer

0 votes
by

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; 
}

Related questions

0 votes
asked Jan 11 in C Plus Plus by GeorgeBell
0 votes
asked Jan 6 in C Plus Plus by GeorgeBell
...