Archived

This topic is now archived and is closed to further replies.

Static keyword in C++

This topic is 5585 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

...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]

Share this post


Link to post
Share on other sites
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]

Share this post


Link to post
Share on other sites
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

Share this post


Link to post
Share on other sites
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]

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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]

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites