通常,人们会在堆栈上声明/分配一个结构:
STRUCTTYPE varname;
Run Code Online (Sandbox Code Playgroud)
这个语法在C中意味着什么(或者只是这个C++,或者可能是VC++特有的)?
STRUCTTYPE varname = {0};
Run Code Online (Sandbox Code Playgroud)
其中STRUCTTYPE是stuct类型的名称,如RECT或其他东西.这段代码编译,似乎只是将结构的所有字节清零,但我想知道是否有人有引用.此外,这个结构有名称吗?
这是聚合初始化,是有效的C和有效的C++.
C++还允许您省略所有初始值设定项(例如零),但对于这两种语言,没有初始化程序的对象是值初始化或零初始化:
// C++ code:
struct A {
int n;
std::string s;
double f;
};
A a = {}; // This is the same as = {0, std::string(), 0.0}; with the
// caveat that the default constructor is used instead of a temporary
// then copy construction.
// C does not have constructors, of course, and zero-initializes for
// any unspecified initializer. (Zero-initialization and value-
// initialization are identical in C++ for types with trivial ctors.)
Run Code Online (Sandbox Code Playgroud)