Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force if statement to execute only once

Tags:

c

I have a piece of code that will be executed many times (5,000+), and an if statement that will be true only the first time. I've thought of using a "FIRST" variable and compare it each time, but it just seems like a waste to check it every single time, even if I know it's not needed.

bool FIRST = true;

void foo(){
if(FIRST){
   /* do something only once */
   FIRST = false;
}
   /* something something... */
}

I also don't know if there is some compiler optimization that does this automatically, or another way to do it; if there is, please let me know.

And yes, I know that a mere if statement isn't a big thing, but it just annoys me.

like image 851
Sophie Nyah Avatar asked Dec 03 '22 17:12

Sophie Nyah


2 Answers

If you're using gcc, there are macros called unlikely and likely that can allow it to make optimizations based on a condition.

In your case the condition will only be true the first time, so you would use unlikely:

if (unlikely(FIRST)) {
like image 88
dbush Avatar answered Dec 14 '22 06:12

dbush


From a compiler optimization point of view, I think an if statement is your best bet, as it will probably compile down to something like a single JNZ, so as long as FIRST stays true, it will be pretty optimized.

You might also want to take a look at this thread

like image 45
tripathiakshit Avatar answered Dec 14 '22 05:12

tripathiakshit