I'm playing around, trying to teach myself C++, and read online that an uninitialized array of integers defaults to an initial value of 0. I run the following code:
1 2
int myArray[5];
cout << myArray[0];
and get the expected outcome of 0.
BUT ...
when I try this code:
1 2 3
int num = 5;
int myArray[num];
cout << myArray[0];
I get the number 161512... which I assume is the integer value of the bits at the memory location.
Then, I try the following code:
1 2 3 4
int num = 5;
int myArray[num];
myArray[2] = 20;
cout << myArray[2];
I predictably get an output of 20.
So, why does it matter if I create an array with the size defined by a variable vs setting the size explicitly?
I apologize in advance if I'm missing something. I understand there are gaps in my knowledge and my exploration (and this post) is trying to fill those gaps.
For that piece of code to be compatible with all compilers, num will need to be declared constant. I can only assume you're using MinGW. Also, the array was never initialised in the code you posted.
justStartinOut wrote:
So, why does it matter if I create an array with the size defined by a variable vs setting the size explicitly?
A variable name gives a magic constant a name so it's easily identified. Plain magic constants offer nothing in terms of readability.
read online that an uninitialized array of integers defaults an initial value of 0.
And that's the problem. Don't trust things you read online and stick to reputable books.
When you don't initialize them, the elements of the array have undefined values, which answers your questions.