Static keyword in C++

Started by
7 comments, last by Demosthenes 21 years, 8 months ago
...I just read in Visual C++'s Help that variables declared with the static keyword only have scope inside the file (in my case, a class file) in which they was declared. So my question is: is there any other operator or a special way to use static so that I can have a "permanent" variable that can be shared between classes? (edited for clarity) [edited by - demosthenes on August 27, 2002 6:25:30 PM]
Advertisement
in one of youre header files:

extern int var;

in one of your source files:

int var;

var now has a global scope through all the source files that include the header file.

Crispy

edit: mistyped extern :/

[edited by - crispy on August 27, 2002 7:15:04 PM]
"Literally, it means that Bob is everything you can think of, but not dead; i.e., Bob is a purple-spotted, yellow-striped bumblebee/dragon/pterodactyl hybrid with a voracious addiction to Twix candy bars, but not dead."- kSquared
Hi

static variables are treated different depending on where they are declared. You are right, when you just declare a variable static outside of any function it will have file-scope.
But when you declare a class member variable static then it is static for this class, meaning that it will have the same value in every instance of the class.
But it has to be initialized to a constant value and can not be changed at runtime.

Hope this helps

------------
Runicsoft
You have a typo..."extern"

Edit: Looks like you got it already


"Wisdom is proportionate to your reference base. Intelligence is the ability to appropriately use that Wisdom."


[edited by - Leathrewulfe on August 27, 2002 7:18:14 PM]
"Wisdom is proportionate to your reference base. Intelligence is the ability to appropriately use that Wisdom."
quote:Original post by Burning_Ice
... and can not be changed at runtime.


That''s incorrect. Static class variables behave the same way that other variables do. If you want it to be constant, you have to use the const keyword, otherwise it''s just a global variable, for all intents and purposes.
daerid@gmail.com
You are right daerid, sorry, got that mixed up

------------
Runicsoft
Ok, thank you all.
Isn't static deprecated in C++ in favour of anonymous namespaces?
EDIT: although if you are sharing the variable amongst multiple files, namespaces won't do.

dMDI

[edited by - dMDI on August 28, 2002 8:17:38 AM]
"I don''t know with what weapons the third world war will be fought, but I know the fourth will be fought with sticks and stones." Einstein
quote:Original post by dMDI
Isn''t static deprecated in C++ in favour of anonymous namespaces?

Yes.
quote:
EDIT: although if you are sharing the variable amongst multiple files, namespaces won''t do.

Neither will static.

This topic is closed to new replies.

Advertisement