Execute a code only one time in C

7.7k Views Asked by At

I want execute a code only one time. I used a solution based on a global varibale of bool type. My question, is it the best solution?

Remark: I use ucos-II.

if (TRUE == Lock)
{
 /*Code to execute one time*/
}

/*The reste of the code*/
3

There are 3 best solutions below

4
On BEST ANSWER

A simple code using a static variable.

static bool once = false;

if (once == false)
{
    once = true;
    // do your "once" stuff here
}
0
On

So if you just use

if (TRUE == Lock)
{
 /*Code to execute one time*/``
}

Lock will ever be true rigth ?

so you need to do

if(Lock == TRUE)
{//code to execute
 Lock = FALSE;
}
0
On

Depends on when you want to do this check and where.

Let's say you have a API like

void func(bool flag)
{
   if(flag)
   {
      // Code for only one condition
   }
   else
   {
     //Rest of the code
   }
}

Then just by passing TRUE or FALSE you can make sure that the required code is executed only once.

Else your approach of having a global variable is also ok but you have to unset your LOCK once the required block is executed

if( LOCK == TRUE)
{
   //Execute code
   LOCK = FALSE;
}

Hope you have a global variable LOCK initialized to 1.

NOTE:

If you are on a flat memory systems it is always dangerous to have global variables so we tend to avoid it. If there is a real need then yes we go for global variable else we can use some flag as suggested in my first approach