Calling a function only once

M

Mark

This is just out of curiosity...

There are a couple ways to make sure a function gets called only once.
Let's say I have a function that gets called several times, called
LoopedFunc() and I have another function called Init() which I only
want to run once... then I can do

LoopedFunc()
{
static bool initialized = false;
if(!initialized) {
Init();
initialized = true;
}
}

or...I can make my Init() function return a boolean and then go

LoopedFunc()
{
static bool this_variable_is_never_used = Init();
}

The second way only requires one line...but still requires a pretty
useless variable, and forces you to put a return on your Init
function.

Shouldn't there be a way to do something like

LoopedFunc()
{
static Init();
}

or something??
 
S

sonison.james

This is just out of curiosity...

There are a couple ways to make sure a function gets called only once.
Let's say I have a function that gets called several times, called
LoopedFunc() and I have another function called Init() which I only
want to run once... then I can do

LoopedFunc()
{
static bool initialized = false;
if(!initialized) {
Init();
initialized = true;
}

}

or...I can make my Init() function return a boolean and then go

LoopedFunc()
{
static bool this_variable_is_never_used = Init();

}

The second way only requires one line...but still requires a pretty
useless variable, and forces you to put a return on your Init
function.

Shouldn't there be a way to do something like

LoopedFunc()
{
static Init();

}

or something??


A crude way of doing it could be...

class Init
{
public:
Init();
};

LoopedFunc()
{
static Init init;
}

Thanks and regards
Sonison James
 
M

Mark

A crude way of doing it could be...

class Init
{
public:
Init();

};

LoopedFunc()
{
static Init init;

}

Thanks and regards
Sonison James

Ahh..that's even worse in my books :p Oh well. I was just wondering.
 

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
474,181
Messages
2,570,970
Members
47,536
Latest member
VeldaYoung

Latest Threads

Top