C++ float array initialization
Solution 1
You only initialize the first N positions to the values in braces and all others are initialized to 0. In this case, N is the number of arguments you passed to the initialization list, i.e.,
float arr1[10] = { }; // all elements are 0
float arr2[10] = { 0 }; // all elements are 0
float arr3[10] = { 1 }; // first element is 1, all others are 0
float arr4[10] = { 1, 2 }; // first element is 1, second is 2, all others are 0
Solution 2
No, it sets all members/elements that haven't been explicitly set to their default-initialisation value, which is zero for numeric types.
Related videos on Youtube
Adam Matan
Team leader, developer, and public speaker. I build end-to-end apps using modern cloud infrastructure, especially serverless tools. My current position is R&D Manager at Corvid by Wix.com, a serverless platform for rapid web app generation. My CV and contact details are available on my Github README.
Updated on June 06, 2020Comments
-
Adam Matan almost 4 years
Possible Duplicate:
C and C++ : Partial initialization of automatic structureWhile reading Code Complete, I came across an C++ array initialization example:
float studentGrades[ MAX_STUDENTS ] = { 0.0 };
I did not know C++ could initialize the entire array, so I've tested it:
#include <iostream> using namespace std; int main() { const int MAX_STUDENTS=4; float studentGrades[ MAX_STUDENTS ] = { 0.0 }; for (int i=0; i<MAX_STUDENTS; i++) { cout << i << " " << studentGrades[i] << '\n'; } return 0; }
The program gave the expected results:
0 0 1 0 2 0 3 0
But changing the initialization value from
0.0
to, say,9.9
:float studentGrades[ MAX_STUDENTS ] = { 9.9 };
Gave the interesting result:
0 9.9 1 0 2 0 3 0
Does the initialization declaration set only the first element in the array?
-
Mark Ransom over 11 yearsDon't forget that you can use an empty initialization list, in which case all elements are set to zero.
-
Ed S. over 11 years@MarkRansom: Yep yep, I'll add that, thanks.
-
Joseph Mansfield over 11 yearsYou make it sound like 0 is a special case, but it's not. It's setting the first element to 0 and then the rest of them to 0.
-
Ed S. over 11 years@sftrabbit: Yep, it does sound that way doesn't it? Thanks.