run once

Started by
6 comments, last by traxxas25 20 years, 4 months ago
how do i run a line of code only once in visual C++?, i want to run this line once: form2*frm = new form2(); so the program doesnt keep creating new copies of that one form or if theres another way to do this tell me please thanks guys
Advertisement

Well, a quick and dirty way (although, not necessarily the best way) is to use a static variable as a flag for initialization.

So, you would do something like this:

static bool initialized = false;

if (!initialized)
{
form2 *frm = new form2();
initialized = true;
}

The first time this code is run, frm will be set up, and on subsequent run throughs of the code, the stuff within the curly braces won''t be run.
otherwise just use a global

-www.penten.tk-
quote:Original post by Anonymous Poster

Well, a quick and dirty way (although, not necessarily the best way) is to use a static variable as a flag for initialization.

So, you would do something like this:

static bool initialized = false;

if (!initialized)
{
form2 *frm = new form2();
initialized = true;
}

The first time this code is run, frm will be set up, and on subsequent run throughs of the code, the stuff within the curly braces won''t be run.


That wouldn''t work too well since the form2 variable is only in scope within the if-statement.

Why not just:

static form2 *frm = new form2(); 


Then you don''t need the static boolean.
that static form2 *frm = new form2(): doesnt work i get a compiler error

error C3145: ''frm'' : cannot declare a global or static managed type object or a __gc pointer
Why use globals?

int& count(){   static int count_ = 0;   return count_;} 


is better, but still undesirable...

could you possibly explain that code and explain were to put it, its alittle confusing, thanks alot!
I didn''t realize you were using managed code. It looks like you will have to use a global.

This topic is closed to new replies.

Advertisement