Skip to main content
gamedev.net
🔒 Locked

static variables

Started by TEUTON 5 replies 600+ views
Original Post
TEUTON
TEUTON
Am I right to say that static variables are same as global variables in C++?
Drew_Benton
Drew_Benton
Nope, static and global variables are two different things that only overlap in one instance - and that is when a static variable is made global.

Take for example this:
int x = 0;void myFunc(){   x++;}

x is a global function that can be access anywhere in your program. If you need it in another file, you can just do: extern int x; in that file and you have access to it. Now consider this example:
void myFunc(){   static int x = 0;   x++;}

x can only be accessed in the myFunc function's scope, and that is it. You could do some hackery and save the address of the variable and use it wherever you need to, but that is beside the point.

So, in short - global variables allow everyone access and have a life time of the entire program. Static variables only allow access in the current scope, and has a life time of the entire program.
Zakwayda
Zakwayda
Quote:
Original post by TEUTON
Am I right to say that static variables are same as global variables in C++?
Static variables in C++ can be different things, for example:

- A single variable shared among all instances of a class
- A persistent variable local to a function or scope
- A variable at file scope

So no, they're not global (although certain uses of them give them some 'global' characteristics).
tuita
tuita
Quote:
Original post by Drew_Benton
Nope, static and global variables are two different things that only overlap in one instance - and that is when a static variable is made global.

To my knowledge, a global static still acts differently to a normal global. The global static will be local to current file it's in.

TEUTON
TEUTON
Basically I thought this because we can access static variables directly by their anywhere. This made me think that they are global variables...
Now it's clear...thank you
Drew_Benton
Drew_Benton
Quote:
Original post by tuita
To my knowledge, a global static still acts differently to a normal global. The global static will be local to current file it's in.


Ah yes, you are correct. Tried it out and the behavior was different (in respect to linking). Cheers!
JohnBolton
JohnBolton
Quote:
Original post by tuita
To my knowledge, a global static still acts differently to a normal global. The global static will be local to current file it's in.


The is no such thing as a global static. That is an oxymoron. A global is accessible from other files. A static (in file scope) is only accessible in the the file that it is defined (and only after the declaration).
John BoltonLocomotive Games (THQ)Current Project: Destroy All Humans (Wii). IN STORES NOW!

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.