开发者

C (or C++?) Syntax: STRUCTTYPE varname = {0};

Normally one would declare/allocate a struct on the stack with:

STRUCTTYPE varname;

What does this syntax mean in C (or is this C++ only, or perhaps specific to VC++)?

STRUCTTYPE varname = {0};

where STRUCTTYPE is the name of a stuct type, like RECT or something. This cod开发者_JS百科e compiles and it seems to just zero out all the bytes of the struct but I'd like to know for sure if anyone has a reference. Also, is there a name for this construct?


This is aggregate initialization and is both valid C and valid C++.

C++ additionally allows you to omit all initializers (e.g. the zero), but for both languages, objects without an initializer are value-initialized or zero-initialized:

// 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.)


In C, the initializer {0} is valid for initializing any variable of any type to all-zero-values. In C99, this also allows you to assign "zero" to any modifiable lvalue of any type using compound literal syntax:

type foo;
/* ... */
foo = (type){0};

Unfortunately some compilers will give you warnings for having the "wrong number" of braces around an initializer if the type is a basic type (e.g. int x = {0};) or a nested structure/array type (e.g. struct { int i[2]; } x = {0};). I would consider such warnings harmful and turn them off.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜