Jump to content
  • Advertisement
Sign in to follow this  
Programmer16

Static variables in functions

This topic is 4815 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

Ok, I'm having problems and I was wondering if static variables in functions span across classes:
class A { void MyFunc() { static int i = 0; i++; }

A MyA1;
A MyA2;
MyA1.MyFunc(); // i = 1
MyA2.MyFunc(); // i = 2

//
MyA1.MyFunc(); // i = 1
MyA2.MyFunc(); // i = 1

My problem is that I have a static float that contains the elapsed time over several seconds (for timing.) In my character class I have an anim instance. I then have 2 character instances. Will both classes use the same static float? I'm assuming so. Thanks!

Share this post


Link to post
Share on other sites
Advertisement
Yes, a static local variable will span across all instances. There is only ONE such variable regardless of how many objects you instanciate. If that's inconvenient to you, use an actual class member (and not a static member either...)

Share this post


Link to post
Share on other sites
As a curiosity, in VB .Net they are implemented behind the scenes as instance members, and as such they are unique per class instance.

C++ probably implements them as static class members.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!