Search code examples
coptimizationgccstatic-variables

How to make a variable inside a function or macro-function that must be defined only one time?


I call CURRENT_DIR(see below) a lot of times in my program. Like the executable path don't change while the program is running, make no sense define it again each time that I call this function.

So, I'm looking for a solution that once this value has set, it should be not set again.

My current solution is: make a static variable with all values set to 0 and in an if-statement test check if the first character if non-null, if true, then set it. But it's looks like a inelegant.. maybe there is a better solution.. by using some model including macros, I do not know.

See the code:

#define CURRENT_DIR ({                                          \
  static char buffer[MAX_PATH + 1] = { 0 };         \
      if(buffer[0] != '\0')                     \
    getcurrentdir(buffer, MAX_PATH);            \
      buffer;                           \
})

Solution

  • Instead of the gcc-specific expression statement, I'd use a function (possibly inlined if desired):

    const char* currentDir(void)
    {
        static char buffer[MAX_PATH + 1] = { 0 };
        if (buffer[0] == '\0')
        {
            getcurrentdir(buffer, MAX_PATH);
        }
        return buffer;
    }
    

    This has a few advantages:

    • It's more portable. (Of course, MAX_PATH and getcurrentdir would be platform-dependent.)
    • It has better type safety. If the string is meant to be constant, you don't want to allow clients to accidentally modify it.

    (The gcc expression statement implementation is broken anyway. The static variable won't be reused across multiple CURRENT_DIR sites in the same scope, and the if test is backwards, so buffer will never be initialized to a non-empty string.)