Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I use {} or {0} to initialise an array/struct? [duplicate]

I have a faint memory of reading that code like int x[4] = {}; used to initialize a struct/array to default values is relying on a non standard (but widespread) extension that first appeared in gcc, and the correct version (as apparently stated in the standard) is int x[4] = { 0 };

Is this correct?

like image 298
user10607 Avatar asked Mar 17 '23 15:03

user10607


1 Answers

In C the initializer list is defined the following way

initializer:
assignment-expression
{ initializer-list }
{ initializer-list , }

While in C++ it is defined the following way

braced-init-list:
{ initializer-list ,opt }
{ }

As you can see C++ allows an empty brace-init list while in C initializer list may not be omitted.

So you may write in C++

int x[4] = {}; 

However in C this definition does not satisfies the Standard (though it can be an implementation-defined language extension). So you have to write

int x[4] = { 0 };

In the both cases elements of the array will be zero-initialized.

like image 200
Vlad from Moscow Avatar answered Apr 01 '23 02:04

Vlad from Moscow