Search code examples
cifndef

How to execute a part of code inside a function only once using #ifndef?


//static int initialized;
void print(struct student *arg) {
  #ifndef first_call
  #define first_call 1
  //if (!initialized) {
    //initialized = 1;
    printf("sizeof(*arg1): %lu\n", sizeof(*arg));
  //}
  #endif
  ...
}

I want to execute lines of code within if block only once.

Of course I know how to do that through different way(commented part).

But I want to know why my code doesn't work as I intended.

Thanks.


Solution

  • A preprocessor directive will happen during compilation. Meaning, before your program will run it will take:

    //static int initialized;
    void print(struct student *arg) {
      #ifndef first_call
      #define first_call 1
      //if (!initialized) {
        //initialized = 1;
        printf("sizeof(*arg1): %lu\n", sizeof(*arg));
      //}
      #endif
      ...
    }
    

    And turn it into:

    //static int initialized;
    void print(struct student *arg) {
      #define first_call 1
      //if (!initialized) {
        //initialized = 1;
        printf("sizeof(*arg1): %lu\n", sizeof(*arg));
      //}
      ...
    }
    

    Which means, what you intended is not going to happen. You simply defined first_call as 1.

    A temporary variable like initialized would be a good solution to make it run once. Do remember though, local variables are destroyed after you exit this function call.. Hint: Look up static variables..

    This would work:

    void print(struct student *arg) 
    {
        static bool initialized = false;
        if (!initialized) 
        {
            initialized = true;
            printf("sizeof(*arg1): %lu\n", sizeof(*arg));
        }
    
        ...
    }