Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C vs C++ initialization of static locals

Tags:

c++

c

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*?

like image 882
Mark Meyer Avatar asked Nov 29 '22 03:11

Mark Meyer


2 Answers

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
}
like image 21
user703016 Avatar answered Dec 05 '22 14:12

user703016


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.

like image 58
Adam Rosenfield Avatar answered Dec 05 '22 12:12

Adam Rosenfield