Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

c

syntax

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

like image 530
Jared Updike Avatar asked Dec 17 '22 17:12

Jared Updike


1 Answers

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.)
like image 84
Fred Nurk Avatar answered Dec 19 '22 06:12

Fred Nurk