Click here to Skip to main content
15,900,258 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
is there anyway to change a function static variable outside function
C++
void foo()
{
   static int count =10;
}


is it possible to change the count value outside function?
Posted
Comments
Sergey Alexandrovich Kryukov 1-Jul-12 3:39am    
Why outside?
--SA
Reza Oruji 1-Jul-12 3:45am    
i am Curious, and have reason
do you like i vote same for your answers?

1 solution

Yes, but you don't want to, otherwise the idea of it being static is completely pointless. If you want to change something then change its visibility, don't hack around the problem.

So in this case you could convert the function into an object:
C++
class f
{
    public:
        f() : count_( 10 ) {}

        void operator()() { // do whatever foo did in here }

        int count_;
};
and make that a static.

Another thing to consider is... statics are really just globals in disguise. They damage the ability of your program to be multithreaded (they require locking) and it's harder to reason about what a program does (they can make it harder to verify a class's invariants).

How about just passing count as a parameter to the funtion:
C++
void foo( int count )
{
    // do whatever foo did before
}
then you get reentrant code for multi-threading, and avoid the whole "set it then call it" model you're aiming for.
 
Share this answer
 
v2
Comments
Sergey Alexandrovich Kryukov 1-Jul-12 3:42am    
Good points, my 5. The OP question could be interpreted as "it it possible without modifying the function", with the trivial answer "no", but this is just a wider view and some rationale.
--SA

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900