Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static variables in C and C++

Is there any difference between a variable declared as static outside any function between C and C++. I read that static means file scope and the variables will not be accessible outside the file. I also read that in C, global variables are static . So does that mean that global variables in C can not be accessed in another file?

like image 405
Naveen Avatar asked Mar 27 '10 07:03

Naveen


People also ask

Where are static variables in C?

The static variables are stored in the data segment of the memory. The data segment is a part of the virtual address space of a program. All the static variables that do not have an explicit initialization or are initialized to zero are stored in the uninitialized data segment( also known as the BSS segment).

Why do we use static variables in C?

static variable is used for a common value which is shared by all the methods and its scope is till the lifetime of whole program. In the C programming language, static is used with global variables and functions to set their scope to the containing file.

Is static used in C?

Static is a keyword used in C programming language. It can be used with both variables and functions, i.e., we can declare a static variable and static function as well. An ordinary variable is limited to the scope in which it is defined, while the scope of the static variable is throughout the program.

Are static variables Global in C?

A global variable can be accessed from anywhere inside the program while a static variable only has a block scope. So, the benefit of using a static variable as a global variable is that it can be accessed from anywhere inside the program since it is declared globally.


2 Answers

No, there's no difference between C and C++ in this respect.

Read this SO answer about what static means in a C program. In C++ there are a couple of other meanings related to the use of static for class variables (instead of instance variables).

Regarding global vars being static - only from the point of view of memory allocation (they are allocated on the data segment, as all globals are). From the point of view of visibility:

static int var;    // can't be seen from outside files
int var;           // can be seen from outside files (no 'static')
like image 158
Eli Bendersky Avatar answered Oct 06 '22 10:10

Eli Bendersky


There are two concepts here "static linkage (or scope)" and static allocation".

Outside a function the keyword refers to linkage, inside it refers to allocation. All variables outside a function have static allocation implicitly. An unfortunate design perhaps, but there it is.

like image 21
Clifford Avatar answered Oct 06 '22 09:10

Clifford