简体   繁体   中英

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 CI get the compilation error "initializer is not constant". Why does it differ between the two? I'm using the VC9 compiler for 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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM