2

I have a question about the syntax in C++ when it comes to declaring arrays. I watched a tutorial where someone used the following code to create the array, but I get errors when running it.

It seems like I can only run the code if I include an = between the [] and the values of the array. Please explain why he doesn't get compiling issues as I did.

#include <iostream>

using namespace std;

int main(void) {
    char vowels[] {'a' ,'e', 'i', 'o', 'u' };

    cout << "\nThe first vowel is: " << vowels[0] << endl;
    cout << "The last vowel is: " << vowels[4] << endl;

    return 0;
}

Output:

main.cpp:10:10: error: definition of variable with array type needs an explicit size or an initializer

  char vowels[] {'a' ,'e', 'i', 'o', 'u' };
              ^
main.cpp:10:18: error: expected ';' at end of declaration

  char vowels[] {'a' ,'e', 'i', 'o', 'u' };
               ^

2 errors generated.
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Andro Yono
  • 29
  • 2

1 Answers1

3

The way you're trying to declare the array:

char vowels[] {'a' ,'e', 'i', 'o', 'u' };

is called extended initializer lists and it's only available from C++11 and above. Ensure your compiler supports this version and above. You may manually use -std=c++11 flag when compiling to verify (since it's not clear which version you're currently using to compile):

$ g++ -std=c++11 -o main main.cpp

Note: It'll work when you use an assignment operator = to assign it which is supported by old compilers:

char vowels[] = {'a' ,'e', 'i', 'o', 'u' };
cigien
  • 57,834
  • 11
  • 73
  • 112
Rohan Bari
  • 7,482
  • 3
  • 14
  • 34