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.
What Does Bracket Mean? Brackets, or braces, are a syntactic construct in many programming languages. They take the forms of "[]", "()", "{}" or "<>." They are typically used to denote programming language constructs such as blocks, function calls or array subscripts. Brackets are also known as braces.
Curly brackets are commonly used in programming languages such as C, Java, Perl, and PHP to enclose groups of statements or blocks of code.
In a Java program, curly braces enclose meaningful units of code. You, the programmer, can (and should) indent lines so that other programmers can see the outline form of your code at a glance.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With