cryptz wrote: |
---|
Would you be willing to explain why my example isn't correct?
I get that your way is proper, but. Why isn't mine?
Is it due to scoping? |
Cryptz, scope does not come into picture here. I think you're a little confused but it's all fine. Consider
int balance[5]
, here balance is an integer array. That means that each element of balance is equivalent to be an integer variable itself.
So what that means is, instead of
1 2 3 4 5
|
cin >> a;
cin >> b;
cin >> c;
cin >> d;
cin >> e;
|
You can directly write:
1 2 3 4 5
|
cin >> balance[0];
cin >> balance[1];
cin >> balance[2];
cin >> balance[3];
cin >> balance[4];
|
(keep in mind that array index start from 0 and not 1)
The above snippet would compile perfectly. In fact it's the equivalent to
1 2 3 4
|
for (int i = 0; i < 5; i++)
{
cin >> balance[i];
}
|
But it's better if you do it with for-loop because it makes it neater and also requires you to type much less.
Coming back to the confusion, when we reach this point at the code in your original snippet:
int balance[5] = {a, b, c, d, e};
the elements of balance (i.e balance[0], balance[1] etc) are being assigned a, b, c, d, e etc.
So it's equivalent to say
1 2 3
|
balance[0] = a;
balance[1] = b;
// and etc.
|
But wait. What is a and what is b? The compiler doesn't know what is a and b and it can't assign just nothing to a variable so the compiler gets confused and complains about it.
Notice that if you initialized the variables to 0, still balance wouldn't change after you changed the values of a, b, c etc (instead it will remain to be 0). Because when you're assigning balance with those variables, you're only assigning their values and you're not holding those variables inside the array.
A good compiler wouldn't compile your script, but if your compiler does not complain then try printing the values of balance[0] and etc., you will get rubbish.
So in short, it's just simpler to use a for-loop like so ;)
1 2 3 4
|
for (int i = 0; i < 5; i++)
{
cin >> balance[i];
}
|