1

i am taking a c++ course and the instructor said to make variables like this:

int main() {
    int myVar {5};
    return 0;
}

this gives me an error: "expected ";" at the end of declaration"

what is wrong?

  • What compiler are you usng and which version of C++ is it supporting? – Jeffrey Jun 20 '20 at 17:48
  • Are you compiling your source file with the exact compiler options your instructor showed you? – StoryTeller - Unslander Monica Jun 20 '20 at 17:48
  • i am using the latest version of geany which uses g++ – user13456653 Jun 20 '20 at 17:49
  • its just this: int main() { int myVar {5}; return 0; } – user13456653 Jun 20 '20 at 17:50
  • 1
    "geany" is an editor. It does not include gcc. Which version of gcc are you using? You must be using a very old version that does not support the current C++ standard, at least by default. – Sam Varshavchik Jun 20 '20 at 17:53
  • 2
    @SamVarshavchik my MacOSX, with relatively recent `Apple LLVM version 10.0.1 (clang-1001.0.46.4)` produce the error above, if we don't tell it to use C++11 – Jeffrey Jun 20 '20 at 17:54
  • That's clang, not gcc. Current version of gcc use C++11 by default. – Sam Varshavchik Jun 20 '20 at 17:55
  • @Jeffrey so if i use a different ide it will work? – user13456653 Jun 20 '20 at 17:56
  • 1
    @user13456653 , you just need to tell it to use C++11: https://stackoverflow.com/questions/14544325/c11-geany-setup – Jeffrey Jun 20 '20 at 17:57
  • @Jeffrey ohh... thank you i was completely lost. – user13456653 Jun 20 '20 at 18:00
  • 2
    @user13456653 One thing missing from a lot of these C++ courses is to let the new programmer know what tools are being used. Just being told about "geany", and not be told what is being done to compile, link, and build your program just leaves you in the dark as to what is really happening. The compiler, which is `g++`, needs to be told what options to use when the compile step is done. The `c++11` option has to be specified. – PaulMcKenzie Jun 20 '20 at 18:01

1 Answers1

3

Uniform initialization requires C++11.

If you use

g++ --std=c++11 [...]

it should work.

test> g++ foo.cpp
foo.cpp:3:6: error: expected ';' at end of declaration
int x{7};
     ^
     ;
1 error generated.
test> g++ --std=c++11 foo.cpp
test>

with

test> more foo.cpp
int main()
{
    int x{7};
}
Jeffrey
  • 11,063
  • 1
  • 21
  • 42