PDA

View Full Version : When declaring an Array...



Joe123
11-09-2008, 06:33 AM
If we can have

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

Then why can't we have

int a; int b; int c; int d; int e;
int MyArray[5] = {a,b,c,d,e};

?

The first one compiles fine, but the second doesn't.

jman2050
11-09-2008, 12:41 PM
Heh, that isn't even allowed in C/C++ last I checked. I remember there being a reason they couldn't do it that way, though it escapes me.

Joe123
11-09-2008, 01:06 PM
Oh, right ok.
Fair enough.

So

int a; int b; int c; int d; int e;
int MyArray[5];
MyArray[0] = a;
MyArray[1] = b;
//etc.
is the most efficient method?

ScaryBinary
11-09-2008, 02:17 PM
So

int a; int b; int c; int d; int e;
int MyArray[5];
MyArray[0] = a;
MyArray[1] = b;
//etc.
is the most efficient method?

That will work, but I don't think it's going to do what you think it's going to do.

(wait...what did I just say? :odd:)

What I mean is, if you do that, and then do something like
a = 10; your array is not going to change - there is no "link" between the integer "a" and your array. So unless you are going to be constantly updating "a", "b" ... "e" and then pushing those values in to your array as in your snippet above, there's really no reason to declare/use the "a", "b" ... "e" variables. Just modify your array directly.

Joe123
11-09-2008, 02:48 PM
What I think it's going to do is load some integers into an array.

I have arguments in an ffc, and I want to load them into an array so I don't have to write out four lots of code.
I know the array's not going to change, I only want to set it once.

ScaryBinary
11-09-2008, 07:01 PM
Gotcha.

On an interesting side note, evidently you can only use positive numbers when you initialize an array at declaration. The following fails to compile (at least in build 819)...
int MyArray_1[5] = {0, 1, 2, -3, 4}; You get an error on the minus sign.

Joe123
11-10-2008, 11:46 AM
Might be linked to the fact that we can't declare negative constants?