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 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*?
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
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With