static keyword inside member function

C

cppaddict

Hi,

I have the following line inside one of my class member functions:

static bool tested = false;
if (!tested) {
MessageBox(NULL, "Hi", "Testing", MB_OK |
MB_ICONEXCLAMATION);
tested = true;
}

The idea, of course, is to have this message box only pop up the first
time the member function is called. However, it doesn't work: the
message box pops up everytime. I know using static inside a normal
function causes the variable to persist. Is there some reason it
won't work inside a member function? Any way I can get it to work?

Thanks for any help,
cpp
 
L

Leor Zolman

Hi,

I have the following line inside one of my class member functions:

static bool tested = false;
if (!tested) {
MessageBox(NULL, "Hi", "Testing", MB_OK |
MB_ICONEXCLAMATION);
tested = true;
}

The idea, of course, is to have this message box only pop up the first
time the member function is called. However, it doesn't work: the
message box pops up everytime. I know using static inside a normal
function causes the variable to persist. Is there some reason it
won't work inside a member function? Any way I can get it to work?

Strange, this looks like it should work fine. There's nothing special about
statics in member functions vs. other functions. See if this works for you;
it should only put up the "dialog box" once:

#include <iostream>
using namespace std;

void stat_test()
{
static bool tested = false;
if (!tested) {
cout << "Displaying dialog box!" << endl;
tested = true;
}
}

int main()
{
stat_test();
stat_test();
stat_test();
return 0;
}

HTH,
-leor
 
C

cppaddict

Strange, this looks like it should work fine. There's nothing special about
statics in member functions vs. other functions. See if this works for you;
it should only put up the "dialog box" once:

Leo,

It was the message box screwing things up. If I do:

static bool tested = false;
if (!tested) {
tested = true;
MessageBox(NULL, "Hi", "Testing", MB_OK |
MB_ICONEXCLAMATION);
}

it works fine.

Thanks,
cpp
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,774
Messages
2,569,599
Members
45,175
Latest member
Vinay Kumar_ Nevatia
Top