开发者

C vs C++ initialization of static locals

I have the following code in both C and C++

static void callback(char const* fname, int status)
{
  static char const* szSection = fname;
  //other stuff
}

In C++ this compiles fine without warning or error. In C I get the compilation error "initializer is not constant". Why does it differ between the two? I'm using the VC9 compiler for开发者_如何学Go Visual Studio 2008 for both.

I'm trying to take a filename as input and set the path to the file the first time. All further callbacks are used to check for updates in the file, but it is not permissible for the path itself to change. Am I using the right variable in a char const*?


Because the rules are different in C and C++.

In C++, static variables inside a function get initialized the first time that block of code gets reached, so they're allowed to be initialized with any valid expression.

In C, static variables are initialized at program start, so they need to be a compile-time constant.


Static variables in functions have to be initialized at compile time.

This is probably what you want:

static void callback(char const* fname, int status)
{
  static char const* szSection = 0;
  szSection = fname;
  //other stuff
}


In C++, I would prefer to do something along these lines:

static void callback(char const* fname, int status)
{
  static std::string section;
  if( section.empty() && fname && strlen(fname) )
  {
    section = fname;
  }
  // other stuff
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜