Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Explicit initialization of struct/class members

struct some_struct{
    int a;
};
some_struct n = {};

n.a will be 0 after this;

I know this braces form of initialization is inherited from C and is supported for compatibility with C programs, but this only compiles with C++, not with the C compiler. I'm using Visual C++ 2005.

In C this type of initialization

struct some_struct n = {0};

is correct and will zero-initialize all members of a structure.

Is the empty pair of braces form of initialization standard? I first saw this form of initialization in a WinAPI tutorial from msdn.

like image 853
Zephon Avatar asked Jun 09 '10 06:06

Zephon


People also ask

How do you initialize struct members?

When initializing an object of struct or union type, the initializer must be a non-empty, (until C23) brace-enclosed, comma-separated list of initializers for the members: = { expression , ... }

Is it possible to initialize structure members while defining a structure?

Structure members cannot be initialized with declaration.

How do you initialize a struct member in C++?

Structure members can be initialized using curly braces '{}'.

What is struct initialization?

An initializer for a structure is a brace-enclosed comma-separated list of values, and for a union, a brace-enclosed single value. The initializer is preceded by an equal sign ( = ).


1 Answers

The empty braces form of initialization is standard in C++ (it's permitted explicitly by the grammar). See C Static Array Initialization - how verbose do I need to be? for more details if you're interested.

I assume that it was added to C++ because it might not be appropriate for a 0 value to be used for a default init value in all situations.

like image 130
Michael Burr Avatar answered Oct 25 '22 07:10

Michael Burr