views:

125

answers:

3

I'd like to declare an array at the top of my method, but it's not compiling:

Foo Bar()
{
    int arr[]; // C2133

    // …

    // C2059, C2143, C2143
    arr[] = {1, 2, 3}; 
}

What am I doing wrong here?

UPDATE I know that C++ doesn't force me to do it this way, but the project's convention wants all variables declared at the top of their method.

+5  A: 

When you declare an array in C/C++, you need to specify the size. If you do not specify the size, then you need to define the array elements in the same declaration statement, like this:

int arr[] = {1, 2, 3};
Alek Davis
In case you don't know the size of the array and cannot specify element at declaration, you need to use pointers and allocate memory dynamically, but this would be a topic for a different question.
Alek Davis
And you'd lose the ability to do the magical "= {1, 2, 3}" if you went with pointers, right?
Owen S.
@Owen Right. Actually, you lose the ability to do that if you don't do it at initialization time, even if the array is declared on the stack with fixed size (i.e. `int arr[3]; arr = {1, 2, 3};` isn't legal). That brace syntax only works for initialization, not assignment.
Tyler McHenry
+4  A: 

It's just invalid syntax. If you want to do arr = { ... };, it has to be when you declare the variable. But C++ doesn't force you to declare the variable at the start of the function, so you could do:

Foo Bar() {
    // other stuff goes here
    // ...
    int arr[] = {1, 2, 3};
}
Karmastan
+1  A: 

You cannot. Either the project's convention needs to give, or your initialization code does:

Foo Bar() {
    int a[3];
    ...
    a[0] = 1;
    a[1] = 2;
    a[2] = 3;
}
Owen S.