Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Global variable and static global variable [duplicate]

Is there any difference in C++ between global variable/const and global static variable/const? Declared in cpp file or a header file.

static const int x1 = someFunction(5);
const int x2 = someFunction(6);
static int x3 = someFunction(5);
int x4 = someFunction(6);

int main()
{
...
like image 263
Random Avatar asked Jun 15 '26 08:06

Random


1 Answers

Case I: For const objects

Similarity

In both versions, the variables have internal linkage. That is, both x1 and x2 have internal linkage.

Difference

In case of static const int x1 the variable is explicitly static while in case of const int x2 the variable is implicitly static. But note that they both still have internal linkage.

Case II:For nonconst objects

Similarity

Both x3 and x4 are nonconst meaning we can modify them.

Difference

The variable x3 has internal linkage while the variable x4 has external linkage.

like image 91
Anoop Rana Avatar answered Jun 17 '26 22:06

Anoop Rana



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!