Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between int x = 5; and int x = {5}

Both of these statements work the same:

int x = 5;
int x = {5};

That's also true when I try:

char str[] = "hello";
char str[] = {"hello"};

How does the language define initializing a variable using curly braces?

like image 477
user3787309 Avatar asked Nov 03 '25 10:11

user3787309


1 Answers

There are three different cases of initialization which apply here:

  • For plain variables/pointers, formally called scalars, then C17 6.7.9 §11 says that you can optionally add braces if you like:

    The initializer for a scalar shall be a single expression, optionally enclosed in braces.

  • Then §14 mentions character arrays specifically - they may be initialized with a string literal. And again they may optionally have braces:

    An array of character type may be initialized by a character string literal or UTF–8 string literal, optionally enclosed in braces.

  • Finally, §16 deals with all other initializers of aggregates (arrays or struct) and unions, braces are no longer optional but mandatory:

    Otherwise, the initializer for an object that has aggregate or union type shall be a brace-enclosed list of initializers for the elements or named members.

This makes it possible to write all initializer lists with consistent syntax and using {} no matter which type that the initializer list is initializing. Which in turn can perhaps be handy when writing type-generic macros and similar.

like image 170
Lundin Avatar answered Nov 05 '25 01:11

Lundin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!