-3

I am facing a problem in the pure embedded c, thats with my logic. There exists a variable text. I am clearing it in one place using

text = NULL;

but this code must be executed only once that too when the first time execution comes to this place.

Please suggest me with the best logic to implement other than using of a flag variable

too honest for this site
  • 12,050
  • 4
  • 30
  • 52
  • 4
    i am not sure if i understand this correct, can you provide proper example code? to me this sounds like a "just do that right in front of the loop" problem – X39 Jun 13 '18 at 13:23
  • 4
    Do you mean every first iteration for a loop or just once in the whole program run? – Ajay Brahmakshatriya Jun 13 '18 at 13:24
  • What do you mean by "first execution"? How many executions will there be? Executions of what? The whole program? A function? The body of a loop? – Yunnosch Jun 13 '18 at 13:28
  • 1
    Reading [ask] might be helpful for making this questions clearer. – Yunnosch Jun 13 '18 at 13:29
  • 1
    On a typical bare metal system, you put the variable inside whatever.c, create a function whatever_init that sets the variable, make the function available through whatever.h and then call that function once from main, before you hit the eternal loop. – Lundin Jun 13 '18 at 15:02
  • Your question is really unclear. Why not just initialize `text` to `NULL` when it is defined? – kkrambo Jun 13 '18 at 16:16

2 Answers2

1

Completly without context the following is a way to implement this. But there might be better ways depending on the circumstances.

To execute a certain bit of code only once in the lifetime of the process, I usually use a construct like this.

static int first_time = 1; // create and initiallize to 1
if (first_time) // equal to first_time != 0
{
  text = NULL;
  first_time = 0;
}

This creates a variable with static storage duration which is initilized to 1 the first time the code is reached. From that point on this variable is present in the corresponding function ( it will not be deleted at the end of the function) and the value only changes with a normal assignment. The initialisation will be skipped in all but the first call, because the variable already exists.

This way you can check whether or not a certain part of the code got executed.

For more information see this

Kami Kaze
  • 2,069
  • 15
  • 27
-1

It's rather unclear exactly what you are looking for, but the other answer covers how to execute your text=NULL line only once on first call of a repeating process and never again. If you're looking to run a process only once upon startup of the microprocessor you can perform it in main() before you begin your repeating while(1) loop.

I.E.

int main(void){
/*Perform one-time on boot initializations here*/
text = NULL;
     while(1){
          /*Repeating code here*/
     }
}
K_Trenholm
  • 482
  • 5
  • 20