Home > Back-end >  "expected expression" error when initializing an empty array [duplicate]
"expected expression" error when initializing an empty array [duplicate]

Time:09-26

I am trying to initialize an empty array that I initialized earlier in the program. However, whenever I compile my program I am given the error

expected an expression (C/C (29))

Here is what my code looks like:

#include <iostream>
using namespace std;

int main(){
    const int MAX_SIZE = 6;
    int array[MAX_SIZE] = {12,-3,24,65,92,11};
    for(int i=0;i<MAX_SIZE;i  ){
        cout << array[i] << " ";
    }
    array[MAX_SIZE] = {};

    return 0;
}

The error is indicated right on the first curly brace of the empty array initialization. Also I am using Visual Studio Code on a Mac OS Big Sur.

CodePudding user response:

Your trouble lies here: array[MAX_SIZE] = {};

The initialization syntax only work when you are initializing an array.

Though it does actually compile for me with GCC, the resulting program then crashes.

If you want to fill the array with a value. Either zero or something else, you may want to use std::fill.

CodePudding user response:

Plain C-style arrays are not assignable, the type array[size] = {...}; syntax is only for declaration and initialisation.

You can use std::array<T,N> instead, like this:

#include <array>
#include <iostream>

using namespace std;

int main(){
    const int MAX_SIZE = 6;
    std::array<int, MAX_SIZE> arr = {12,-3,24,65,92,11};

    for(int i=0;i<MAX_SIZE;i  ){
        cout << arr[i] << " ";
    }
    
    // reset all elements back to 0
    arr.fill(0);

    return 0;
}

CodePudding user response:

This expression:

array[MAX_SIZE] = {};

Attempts to assign a value at index 6 to something that isn't an array. That's why it generates a compiler error. (And if it didn't, it would be assigning something to an invalid index in an array!)

You might be temped to think this...

array = {};

...would work, since it's similar for resetting members of objects to a default initialized state. But it doesn't work for arrays.

But this works:

std::fill(a, a MAX_SIZE, 0);  // #include <algorithm> if needed

And will assign every element in a to 0

Old school, "C" way for doing the same thing:

memset(a, '\0', MAX_SIZE*sizeof(int));  // #include <string.h> if needed

Or just manually

for (int i = 0; i < MAX_SIZE; i  ) {
    a[i] = 0;
}
  •  Tags:  
  • c
  • Related