C vs C ++ initialization of static locales

I have the following code in C and C ++

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

In C ++, this compiles without warning or error. In C, I get a compilation error "initializer is not constant." Why is it different from two? I am using the VC9 compiler for Visual Studio 2008 for both.

I am trying to take the file name as input and set the file path for the first time. All subsequent callbacks are used to check for updates in the file, but the path itself cannot be changed. Am I using the right variable in char const *?

+4
source share
3 answers

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

In C ++, static variables inside a function get initialized the first time they reach a block of code, so they are allowed to initialize any valid expression.

In C, static variables are initialized when the program starts, so they must be a compile-time constant.

+18
source

Static variables in functions must 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 } 
+2
source

In C ++, I would prefer to do something in this direction:

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

All Articles