静态本地的C与C ++初始化

时间:2022-12-08 01:55:35

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

我在C和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.

在C ++中,这可以在没有警告或错误的情况下编译。在C中我得到编译错误“初始化程序不是常量”。为什么两者之间有所不同?我正在为Visual Studio 2008使用VC9编译器。

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

我正在尝试将文件名作为输入,并在第一次设置文件的路径。所有进一步的回调都用于检查文件中的更新,但路径本身不允许更改。我在char const *中使用了正确的变量吗?

3 个解决方案

#1


18  

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

因为C和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.

在C ++中,函数内部的静态变量在第一次到达代码块时被初始化,因此允许使用任何有效表达式对它们进行初始化。

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

在C中,静态变量在程序启动时初始化,因此它们需要是编译时常量。

#2


2  

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
}

#3


1  

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

在C ++中,我更愿意沿着这些方向做点什么:

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

#1


18  

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

因为C和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.

在C ++中,函数内部的静态变量在第一次到达代码块时被初始化,因此允许使用任何有效表达式对它们进行初始化。

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

在C中,静态变量在程序启动时初始化,因此它们需要是编译时常量。

#2


2  

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
}

#3


1  

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

在C ++中,我更愿意沿着这些方向做点什么:

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