# How do I ensure a piece of code runs only once?

I have some code that I only want to run once, even though the circumstances that trigger that code could happen multiple times.

For example, when the user clicks the mouse, I want to click the thing:

void Update() {
if(mousebuttonpressed) {
ClickTheThing(); // I only want this to happen on the first click,
// then never again.
}
}


However, with this code, every time I click the mouse, the thing gets clicked. How can I make it happen only once?

• I actually find this kinda of funny as I don't think it falls within "game-specific programming issues". But I never really liked that rule. – ClassicThunder Mar 25 '16 at 23:33
• @ClassicThunder Yep, it's certainly more on the general programming side of things. Vote to close if you like, I posted the question more so we'd have something to point people to when they ask similar questions to this. It can be open or closed for that purpose. – MichaelHouse Mar 26 '16 at 0:35
• PPCG's got you covered. – SirPython Mar 26 '16 at 21:14

Use a boolean flag.

In the example shown, you'd modify the code to be something like the following:

//a boolean flag that lets us "remember" if this thing has happened already
bool thatThingHappened = false;

void Update() {
if(!thatThingHappened && mousebuttonpressed) {
//if that thing hasn't happened yet and the mouse is pressed
thatThingHappened = true;
ClickTheThing();
}
}


Further, if you wanted to be able to repeat the action, but limit frequency of the action (i.e. the minimum time between each action). You'd use a similar approach, but reset the flag after a certain amount of time. See my answer here for more ideas on that.

• The obvious answer to your question :-) I'd be interested to see alternative approaches if you or anyone else know of any. This use of a global Boolean for this has always been smelly to me. – Evorlor Mar 25 '16 at 17:29
• @Evorlor Not obvious to everyone :). I'm interested in alternative solutions as well, maybe we can learn something not so obvious! – MichaelHouse Mar 25 '16 at 17:32
• @Evorlor as an alternative, you could use delegates (function pointers) and change what action is made. e.g. onStart() { delegate = doSomething; } ... if(mousebuttonpressed) { delegate.Execute(); } and void doSomething() { doStuff(); delegate = funcDoNothing; } but in the end all options end up having a flag of some sorts you set/unset... and delegate in this case is nothing else(except if you have more than two options what to do perhaps?). – wondra Mar 25 '16 at 17:50
• @wondra Yeah, that's a way. Add it. We might as well make a list of possible solutions on this question. – MichaelHouse Mar 25 '16 at 18:00
• @JamesSnell More likely if it was multi-threaded. But still a good practice. – MichaelHouse Mar 25 '16 at 21:49

Should bool flag not suffice or you wanted to improve readability* of the code in void Update() method, you could consider using delegates (function pointers):

public class InputController
{
//declare delegate type:
//<accessbility> delegate <return type> <name> ( <parameter1>, <paramteter2>, ...)
public delegate void ClickAction();

//declare a variable of that type
public ClickAction ClickTheThing { get; set; }

void onStart()
{
//assign it the method you wish to execute on first click
ClickTheThing = doStuff;
}

void Update() {
if(mousebuttonpressed) {
//you simply call the delegate here, the currently assigned function will be executed
ClickTheThing();
}
}

private void doStuff()
{
//some logic here
ClickTheThing = doNothing; //and set the delegate to other(empty) funtion
}

//or do something else
private void doNothing(){}
}


For simple "execute once" delegates are overkill, so I would suggest using bool flag instead.
However, if you needed more complicated functionality, the delegates are probably better choice. For example, if you wanted to chain execute more different actions: one on first click, other one on second and one more on third you could just do:

func1()
{
//do logic 1 here
someDelegate = func2;
}

func2()
{
//do logic 2 here
someDelegate = func3;
}
//etc...


*at cost of lower maintainability of the rest of the code

I did some profiling with results pretty much as I expected:

----------------------------------------
|     Method     |  Unity   |    C++   |
| -------------------------------------|
| positive flag  |  21 ms   |   6 ms   |
| negative flag  |  5 ms    |   7 ms   |
| delegate       |  25 ms   |   14 ms  |
----------------------------------------


The first test was run on Unity 5.1.2, measured with System.Diagnostics.Stopwatch on 32-bit built project (not in designer!). The other one on Visual Studio 2015 (v140) compiled in 32-bit release mode with /Ox flag. Both tests were run on Intel i5-4670K CPU @ 3.4GHz, with 10,000,000 iterations for each implementation. code:

//positive flag
if(flag){
doClick();
flag = false;
}
//negative flag
if(!flag){ }
else {
doClick();
flag = false;
}
//delegate
action();


conclusion: While the Unity compiler does a good job when optimizing function calls, giving roughly same result for both positive flag and delegates (21 and 25 ms respectively) the branch misprediction or function call is still quite expensive (note: delegate should be assumed cache in this test).
Interestingly, Unity compiler is not smart enough optimize the branch when there are 99 millions of consecutive mispredictions, so manual negating of the test does yield some performance boost giving best result of 5 ms. The C++ version does not show any performance boost for negating condition, however the overall overhead of function call is significantly lower.
most importantly: the difference is pretty much irrelevat for any real-world scenario

• AFAIK this is better from a performance point of view, too. Calling a no-op function, assuming that function is already in the instruction cache, is a lot quicker than checking flags, especially where that checking is nested under other conditionals. – Engineer Mar 26 '16 at 9:40
• I think Navin is right, I it likely to have worse performance than checking boolean flag - unless your JIT is really smart and replaces whole function with literally nothing. But unless we profile the results, we cannot know for sure. – wondra Mar 26 '16 at 19:29
• Hmm, this answer reminds me of the evolution of a SW engineer. Joke aside, if you absolutely need (and are sure) of this performance boost, go for it. If not, I'd suggest to keep it KISS and use a boolean flag, like proposed in another answer. However, +1 for the alternative represented here! – mucaho Mar 26 '16 at 21:26
• Avoid conditionals where possible. I'm talking about what happens at the machine level, whether that's your own native code, a JIT compiler, or an interpreter. L1 cache hit is about the same as a register hit, possibly slightly slower i.e. 1 or 2 cycles, whereas branch misprediction, which happens less often but still too much on average, costs on order of 10-20 cycles. See Jalf's answer: stackoverflow.com/questions/289405/… And this: stackoverflow.com/questions/11227809/… – Engineer Mar 27 '16 at 5:36
• Remember furthermore that these conditionals in Byte56's answer have to be called every single update for the lifetime of your program, and may well be nested or have nested conditionals within them, making matters far worse. Function pointers / Delegates are the way to go. – Engineer Mar 27 '16 at 5:41

### For completeness

(Not actually recommending that you do this as it's actually pretty straightforward to just write something like if(!already_called), but it would be "correct" to do it.)

Unsurprisingly, the C++11 standard has idiomized the rather trivial problem of calling a function once, and made it super explicit:

#include <mutex>

void Update() {
if(mousebuttonpressed) {
static std::once_flag f;
std::call_once(f, ClickTheThing);
}


}

Admittedly, the standard solution is somewhat superior to the trivial one in presence of threads since it still guarantees that always exactly one call happens, never something different.

However, you aren't normally running a multithreaded event loop and pressing the buttons of several mice at the same time, so that thread safety is a bit superfluous for your case.

In practical terms, it means that in addition to the thread-safe initialization of a local boolean (which C++11 guarantees to be thread-safe anyway), the standard version must also do an atomic test_set operation prior to calling or not calling the function.

Still, if you like being explicit, there's the solution.

EDIT:
Huh. Now that I've been sitting here, staring at that code for some minutes, I'm almost inclined to recommend it.
Actually it is not nearly as silly as it may seem at first, indeed it very clearly and unambiguously communicates your intent... arguably better structured and more readable than any other solution which involves an if or such.

Some suggestions will vary depending on architecture.

Create clickThisThing() as a function pointer / variant / DLL / so / etc... and ensure that it is initialized to your required function when the object / component / module / etc... is instantiated.

In the handler whenever mouse button is pressed then call the clickThisThing() function pointer and then immediately replace the pointer with another NOP (no operation) function pointer.

No need for flags and extra logic for someone to screw up later, just call it and replace it every time and since it's a NOP the NOP does nothing and gets replaced with a NOP.

Or you could use the flag and logic to skip the call.

Or you could disconnect the Update() function after the call so the outside world forgets about it and never calls it again.

Or you have the clickThisThing() itself use one of these concepts to only respond with useful work once. This way you can use a baseline clickThisThingOnce() object / component / module and instantiate it anywhere you needed this behavior and none of your updaters need special logic all over the place.

Use function pointers or delegates.

The variable holding the function pointer need not be explicitly examined until a change needs to be made. And when you no longer need said logic to run, replace with a ref to an empty / no-op function. Compare with doing conditionals checks every frame for the entire life of your program - even if that flag was only needed in the first few frames after startup! - Unclean and inefficient. (Boreal's point about prediction is however acknowledged in this regard.)

Nested conditionals, which these often constitute, are even more costly than having to check one single conditional every frame, since branch prediction can no longer do its magic in that case. That means regular delays on the order of 10s of cycles - pipeline stalls par excellence. The nesting can occur above or below this boolean flag. I hardly need remind readers of how complex game loops can quickly become.

Function pointers exist for this reason - use them!

• We're thinking along the same lines. The most efficient way would be to disconnect the Update() thing from whoever keeps calling it relentlessly once it's done the work, which is very common in Qt style signal+slot setups. The OP didn't specify the runtime environment so we're hamstrung when it comes to specific optimizations. – Patrick Hughes Mar 27 '16 at 6:39

In some script languages like javascript or lua can be easly done testing the function reference. In Lua (love2d) :

function ClickTheThing()
.......
end
....

local ctt = ClickTheThing  --I make a local reference to function

.....

function update(dt)
..
if ctt then
ctt()
ctt=nil
end
..
end


In a Von Neumann Architecture computer, memory is where your program's instructions and data are stored. If you want to make code only run once, you could have code in the method overwrite the method with NOP's after the method is complete. This way if the method were to run again, nothing would happen.

• This will break a few architectures that write protect program memory or run from ROM. It will also possibly set off random antivirus warnings, depending on what is installed. – Patrick Hughes Mar 27 '16 at 6:57

In python if your planning on being a jerk to other people on the project:

code = compile('main code'+'del code', '<string>', 'exec')
exec code


this script demonestrates the code:

from time import time as t

code = compile('del code', '<string>', 'exec')

print 'see code object:'
print code

while True:
try:
user = compile(raw_input('play with it (variable name is code) (type done to be done:\t'), '<user_input>', 'exec')
exec user
except BaseException as e:
print e
break

exec code

print 'no more code object:'
try:
print code
except BaseException as e:
print e

while True:
try:
user = compile(raw_input('try to play with it again (type done to be done:\t'), '<user_input>', 'exec')
exec user
except BaseException as e:
print e
break


Here's another contribution, it's a little more general/reusable, slightly more readable and maintainable, but likely less efficient than other solutions.

Let's encapsulate our once-executing logic in a class, Once:

class Once
{
private Action body;
public bool HasBeenCalled { get; private set; }
public Once(Action body)
{
this.body = body;
}
public void Call()
{
if (!HasBeenCalled)
{
body();
}
HasBeenCalled = true;
}
public void Reset() { HasBeenCalled = false; }
}


Using it like the example provided looks as follows:

Once clickTheThingOnce = new Once(ClickTheThing);

void Update() {
if(mousebuttonpressed) {
clickTheThingOnce.Call(); // ClickTheThing is only called once
// or until .Reset() is called
}
}


You can consider using static a variable.

void doOnce()
{
static bool executed = false;

if(executed == false)
{
executed = true;
}
}


You can do this in ClickTheThing() function itself, or create another function and call ClickTheThing() in the if body.

It is similar to the idea of using a flag as suggested in other solutions, but the flag is protected from other code and cannot be altered elsewhere due to being local to the function.

• ...but this prevents you from having the code run once 'per object instance'. (If that's what the user needs.. ;)) – Vaillancourt Mar 30 '16 at 13:01

I actually came across this dilemma with Xbox Controller Input. Although not EXACTLY the same it's pretty damn similar. You can change the code in my example to suit your needs.

Edit: Your situation would use this ->

https://docs.microsoft.com/en-us/windows/desktop/api/winuser/ns-winuser-tagrawmouse

And you can learn how to create a raw input class via ->

https://docs.microsoft.com/en-us/windows/desktop/inputdev/raw-input

But.. now onto the super awesome algorithm... not really, but hey.. it's pretty cool :)

*So... we can store the states of every button and which are Pressed, Released, and Held Down!!! We can also check Holding Time, but that does require a single if statement and can check any number of buttons, but there are some rules see below for this information.

Obviously if we want to check if something is pressed, released, etc.. you would do "If(This) { }", but this is showing how we can get the press state and then turn it off the next frame so your "ismousepressed" will actually be false the next time you check.

How it works..

So I'm not sure the values you receive when you depict if a button is pressed or not, but basically when I load in XInput I get a 16bit value between 0 and 65535 this has 15 bits possible states for "Pressed".

The problem was every time I checked this It would simply give me the current state of the information. I needed a way to convert the current state into Pressed, Released, and Hold Values.

So what I did is the following.

First we create a "CURRENT" variable. Every time we check this data we set the "CURRENT" to a "PREVIOUS" variable and then store the new data to "Current" as seen here ->

uint64_t LAST = CURRENT;


With this information here's where it get's exciting!!

We can now figure out if a Button is being HELD DOWN!

BUTTONS_HOLD = LAST & CURRENT;


What this does is basically it compares the two values and any button presses that are shown in both will stay 1 and everything else set to 0.

I.e. (1 | 2 | 4) & (2 | 4 | 8) will yield (2 | 4).

Now that we have which buttons are "HELD" down. We can get the rest.

Pressed is simple.. we take our "CURRENT" state and remove any held down buttons.

BUTTONS_PRESSED = CURRENT ^ BUTTONS_HOLD;


Released is the same only we compare it to our LAST state instead.

BUTTONS_RELEASED = LAST ^ BUTTONS_HOLD;


So looking at the Pressed situation. If let's say Currently we had 2 | 4 | 8 pressed. We found that 2 | 4 where held. When we remove the Held Bits we are left with only 8. This is the newly pressed bit for this cycle.

The same can be applied for Released. In this scenario "LAST" was set to 1 | 2 | 4. So when we remove the 2 | 4 bits. We are left with 1. So the button 1 was released since the last frame.

This above scenario is probably the most ideal situation you can offer for bit comparison and it provides 3 levels of data with no if statements or for loops just 3 quick bit calculations.

I also wanted to document hold data so although my situation isn't perfect... what it does is we basically set the holdbits we want to check for.

So every time we set our Press/Release/Hold data we check if the hold data still equals the current hold bit check. If it doesn't we reset it's time to current time. In my case I'm setting it to frame indexes so I know how many frames it's been held down for.

The downside to this approach is I can't get individual hold times, but you can check multiple bits at once. I.e. if I set the hold bit to 1 | 16 if either 1 or 16 are not held this would fail. So it requires that ALL those buttons are held down to continue ticking.

Then if you look in the code you'll see all the neat function calls.

So your example would be reduced to simply checking if a button press occurred and a button press can only occur once with this algorithm. On the next check to press it will not exist since you can't press more then once you'd have to release before you can press again.

• So you basically use a bitfield instead of a bool as stated in the other answers? – Vaillancourt Jan 9 at 17:34
• Yeah pretty much lol.. – Jeremy Trifilo Jan 9 at 19:09
• It can be used for his requirements though with the below msdn struct the "usButtonFlags" contains a single value of all the button states. docs.microsoft.com/en-us/windows/desktop/api/winuser/… – Jeremy Trifilo Jan 9 at 19:19
• I'm not sure where the necessity to say all this about controller buttons comes from, though. The core content of the answer is hidden beneath a lot of distracting text. – Vaillancourt Jan 9 at 19:28
• Yeah I was just giving a related personal scenario and what I did to accomplish it. I'll clean it up later though for sure and maybe I'll add Keyboard and Mouse input and give an approach towards that. – Jeremy Trifilo Jan 9 at 21:21

Stupid cheap way out but you could use a for loop

for (int i = 0; i < 1; i++)
{
//code here
}

• The code in the loop will always be executed when the loop is run. Nothing in there is preventing the code from being executed once. The loop or no loop gives exactly the same result. – Vaillancourt Apr 1 '16 at 16:59