Internal static variables in C, would you use them?

后端 未结 13 1489
甜味超标
甜味超标 2020-12-07 19:09

In C you can have external static variables that are viewable every where in the file, while internal static variables are only visible in the function but is persistent

13条回答
  •  [愿得一人]
    2020-12-07 19:40

    I find it handy for one-time, delayed, initialization:

    int GetMagic()
    {
       static int magicV= -1;
    
       if(-1 == magicV)
       {
          //do expensive, one-time initialization
          magicV = {something here}
       }
       return magicV;
    }
    

    As others have said, this isn't thread-safe during it's very first invocation, but sometimes you can get away with it :)

提交回复
热议问题