5

The following snippet compiles perfectly with C/C++ compiler:

#include <stdio.h>
int main()
{
    int x = {5};         //<-- why this compiles?
    printf("x = %d",x);
    return 0;
}

The output is 5. x is initialized here in a compound-type form although it's of integral type. I would like to understand what conversions are made here and why.

SomeWittyUsername
  • 18,025
  • 3
  • 42
  • 85

2 Answers2

8

C allows it in:

(C99, 6.7.8p11) "The initializer for a scalar shall be a single expression, optionally enclosed in braces."

C++ has a similar rule in C++11, 8.5.4p1

ouah
  • 142,963
  • 15
  • 272
  • 331
3

There is no convertions made here, it is standard defined way of variable initialisation.

8.5.4 List-initialization [dcl.init.list]

1 List-initialization is initialization of an object or reference from a braced-init-list. Such an initializer is called an initializer list, and the comma-separated initializer-clauses of the list are called the elements of the initializer list. An initializer list may be empty. List-initialization can occur in direct-initialization or copy- initialization contexts; list-initialization in a direct-initialization context is called direct-list-initialization and list-initialization in a copy-initialization context is called copy-list-initialization.
[Note: List-initialization can be used — as the initializer in a variable definition (8.5)
...
[ Example: int a = {1};

David G
  • 94,763
  • 41
  • 167
  • 253
alexrider
  • 4,449
  • 1
  • 17
  • 27