Sign in to follow this  
Programmer16

Static variables in functions

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

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this