Search code examples
c++initializationdeclarationcurly-braces

Use of Curly Brackets (Braces) Around a variable C++


I'm learning 2D arrays in my programming class. My teacher used something without explaining it and I was curious why we used it. Since it has to do with a symbol I'm not sure how to google or search for it, as these symbols are used in the search itself. Anyways the code was this:

int small[26]= {0}, large[26]={0}, i;

Why are the curly braces needed around the 0's?

The program this code is a part of examines a file and looks for each letter of the alphabet and counts them individually.


Solution

  • It could be written even simpler

    int small[26]= {}, large[26]={}, i;
    

    The curly brackets means an initializer list in this case of arrays.

    Let assume for example that you want to define an array with elements 1, 2, 3, 4, 5.

    You could write

    int a[5];
    
    a[0] = 1;
    a[1] = 2;
    a[2] = 3;
    a[3] = 4;
    a[4] = 5;
    

    However C++ allows to assign elements of an array when it is defined. The equivalent record will look

    int a[5] = { 1, 2, 3, 4, 5 };
    

    If there are initializers less than the size of the array then remaining elements will be initialized by zeroes. For example

    int a[5] = { 1, 2 };
    

    In this case a[0] will be equal tp 1 a[1] will be equal to 2 and all other elements will be equal to 0.

    You may omit the size of an array. For example

    int a[] = { 1, 2, 3, 4, 5 };
    

    In this case the compiler will allocate as many elements of the array as there are initializers in the initializer list.

    Record (valid only in C++. In C it is not allowed)

    int a[5] = {};
    

    is equivalent to

    int a[5] = { 0 };
    

    that is all elements of the array will be initialized by 0. In the last record the first element is initialized explicitly by zero and all other elements are also initialized by zero because their initializers in the initializer list were not specified.

    The same way you can initialize also scalar objects. For example

    int x = { 10 };

    The only difference that for scalar objects you can specify only one initializer. You even may write without the assignment operator

    int x { 10 };
    

    You also can write

    int x {};
    

    In this case x will be initialized by 0.