c++ compile error 'expected ';' at end of declaration' when using direct brace initialization
Asked Answered
P

5

15

I'm very new to C++, working through my first tutorial, and when I try to compile code from the lesson, I get the following error:

expected ';' at end of declaration
    int x{ }; // define variable x to hold user input (a...
         ^
         ;

The full code for the program I'm attempting to run:

#include <iostream>  // for std::cout and std::cin
 
int main()
{
    std::cout << "Enter a number: ";
    int x{ }; 
    std::cin >> x; 
    std::cout << "You entered " << x << '\n';
    return 0;
}

I am using Visual Studio Code (v.1.46.1) on a Macbook Pro, with the Microsoft C/C++ extension (https://marketplace.visualstudio.com/items?itemName=ms-vscode.cpptools).

My compiler is Clang:

Apple clang version 11.0.3 (clang-1103.0.32.62)
Target: x86_64-apple-darwin19.5.0
Thread model: posix
InstalledDir: /Library/Developer/CommandLineTools/usr/bin

Initially, I ran Terminal > Configure Default Build Task in VS Code to create a .vscode/tasks.json compiler settings file. That file currently looks like this:

{
    "version": "2.0.0",
    "tasks": [
    {
      "type": "shell",
      "label": "C/C++: clang++ build active file",
      "command": "/usr/bin/clang++",
      "args": [
        // Set C++ Standards 
        "-std=c++17",

        // Increase compiler warnings to maximum
        "-Wall",
        "-Weffc++",
        "-Wextra",
        "-Wsign-conversion",

        // Treat all warnings as errors
        "-Werror",

        // Disable compiler extensions
        "-pedantic-errors",

        // File to compile
        "-g",
        "${file}",

        // Output file
        "-o",
        "${fileDirname}/${fileBasenameNoExtension}"
      ],
      "options": {
        "cwd": "${workspaceFolder}"
      },
      "problemMatcher": [
        "$gcc"
      ],
      "group": {
        "kind": "build",
        "isDefault": true
      }
    }
  ]
}

I have the -std=c++17 flag set, which should allow direct brace initialization from what I understand.

I'm not sure it matters, since I'm trying to compile and not build/debug, but for the sake of thoroughness, I also have a .vscode/launch.json file with the following contents:

{
  "version": "0.2.0",
  "configurations": [
    {
      "name": "clang++ - Build and debug active file",
      "type": "cppdbg",
      "request": "launch",
      "program": "${fileDirname}/${fileBasenameNoExtension}",
      "args": [],
      "stopAtEntry": true,
      "cwd": "${workspaceFolder}",
      "environment": [],
      "externalConsole": false,
      "MIMode": "lldb",
      "preLaunchTask": "C/C++: clang++ build active file"
    }
  ]
}

Can someone help me figure out why int x{ }; is not working properly to intitialize the variable and what I can do to fix it so it will work?

[Edit]: Further settings I've checked/tested:

  • Code compiles correctly when running compile directly from command line with clang++ -std=c++17 -g helloworld.cpp -o helloworld
  • VS Code C/C++ extension configuration has setting 'C++ standard' set to c++17 (seems to be the default). Even so, running command-line compile without -std=c++17 flag set causes same compiler error.
  • Tried changing int x{ }; to the following:
    • int x( );: fails with a very long list of errors
    • int x(0);: compiles successfully
    • int x = { };: compiles successfully
    • int x = {0};: compiles successfully
    • `int x;': compiles successfully
    • `int x = 0;': compiles successfully
Proclaim answered 20/6, 2020 at 15:7 Comment(14)
Can you compile it on the command line, or does that also produce an error?Noggin
What's the name of your source file, including the extension? clang deduces the language from the filename, and it's possible it thinks this is something other than C++. Also, are there any other errors besides the one shown?Mcclary
@Noggin yes it does compile from the command line with ``` clang++ -std=c++17 -Wall -Weffc++ -Wextra -Wsign-conversion -Werror -pedantic-errors -g helloworld.cpp -o helloworld ``` It also compiles just fine when I remove all the optional flags on the command line, like so: ``` clang++ -std=c++17 -g helloworld.cpp -o helloworld ```Proclaim
@NateEldredge source file is called helloworld.cpp. This is the only error I get. Full console output is: ``` Executing task: /usr/bin/clang++ -g /Users/{redacted}/Documents/development/c++/learncpp/helloworld/helloworld.cpp -o /Users/{redacted}/Documents/development/c++/learncpp/helloworld/helloworld < /Users/{redacted}/Documents/development/c++/learncpp/helloworld/helloworld.cpp:6:10: error: expected ';' at end of declaration int x{ }; ^ ; 1 error generated. The terminal process terminated with exit code: 1 ```Proclaim
The -std=c++17 is obviously not being passed, and your compiler is old enough to default to C++03, where that syntax doesn’t work.Onions
@DavisHerring c++03 would not compile int x = {0};Caesura
Are you sure this is a real compilation error and not some kind of instant syntax assistant message?Caesura
@n.'pronouns'm.: C++03 does allow that syntax ([dcl.init]/13); the braces are ignored.Onions
@DavisHerring what about int x={};? Anyway the compiler is based on llvm9 which is not old enough to default to c++03.Caesura
perhaps /usr/bin/clang++ is not the version you run from the command line?Caesura
@n.'pronouns'm. in C++03 and in C, a scalar may be initialized by = with a single expression in braces. The C++11 extensions included empty braces, and omitting the = symbolWhitneywhitson
@M.Layton the "full console output" you posted in comments shows that your expected flags are not passed, so this is a problem with vscode configuration (not with your program)Whitneywhitson
Does it compile on the command like without ` -std=c++17`? The version of clang is new enough to default to c++14 I think...Caesura
solution for this problem is here #55116844Rainey
S
7

I had the same issue and there was an error in my tasks.json. This worked for me, try it:

{
    // See https://go.microsoft.com/fwlink/?LinkId=733558
    // for the documentation about the tasks.json format
    "version": "2.0.0",
    "tasks": [
      {
        "type": "shell",
        "label": "clang++ build active file",
        "command": "/usr/bin/clang++",
        "args": [
          "-std=c++17",
          "-stdlib=libc++",
          "-g",
          "${file}",
          "-o",
          "${fileDirname}/${fileBasenameNoExtension}"
        ],
        "options": {
          "cwd": "${workspaceFolder}"
        },
        "problemMatcher": ["$gcc"],
        "group": {
          "kind": "build",
          "isDefault": true
        }
      }
    ]
  }
Summon answered 26/2, 2021 at 13:54 Comment(2)
The missing line is probably "-std=c++17",Brittenybrittingham
@Brittenybrittingham that line is not missing from the question post.Glyconeogenesis
C
1

I had exactly the same problem, I tried to modify tasks.json, c_cpp_properties.json and settings.json but nothing worked. I finally tried the solution shown here, which is to disable the C/C++ Clang Command Adapter extension, and it worked for me!

Cott answered 3/8, 2022 at 7:30 Comment(0)
K
0

Refering to this explanation of List initialization, this syntax should be legal since c++11:

int main()
{
    int n0{};     // value-initialization (to zero)
    int n1{1};    // direct-list-initialization
    //...
}

I attempted to compile your code in my local environment and all worked fine:

clang++ -std=c++17 -Wall -Weffc++ -Wextra -Wsign-conversion -Werror -pedantic-errors ...

clang++ --version
clang version 9.0.1 
Target: x86_64-pc-linux-gnu
Thread model: posix

Maybe you used some similar ';' character which is not ASCII?
I attempted to use a Chinese character ';' instead and get this:

fly.cc:32:13: error: treating Unicode character <U+FF1B> as identifier character rather than as ';' symbol [-Werror,-Wunicode-homoglyph]
    int x{ }; 
            ^~
fly.cc:32:13: error: expected ';' at end of declaration
    int x{ }; 
            ^
            ;
Kreit answered 21/6, 2020 at 8:35 Comment(1)
That's not actually a Chinese character, just a fullwidth semicolon...Muezzin
U
0

I was stuck on this for a while as well. Here is the command that got it working for me:

clang++ helloworld.cpp -o helloworld -std=c++17 && "<YOUR PATH TO THE FILE INSIDE THE QUOTES>"helloworld

E.g. "< YOUR PATH TO THE FILE INSIDE THE QUOTES >" = "/Users/< your username >/<something else>/"helloworld

I also installed the extension code runner and then searched in settings for run in terminal then checked the box which said Code-runner: Run in terminal.

You should also be able to search for C++ in the settings as well and then set a default Cpp standard, but this never worked for me so I had to add it in the command.

Urbana answered 14/8, 2022 at 17:3 Comment(0)
R
0

For those who have this problem with code runner, the problem is that we do not specify to code runner which version to use, for that, go to the installed extensions > code runner > extension configuration > edit in settings.json look in code-runer.executorMap:

the line that says cpp in my case is on line of code 21. after $filename you put -std=c++17

// It should look similar to this
"cpp": "cd $dir && g++ $fileName -std=c++17 -o $fileNameWithoutExt && $dir$fileNameWithoutExt"

It worked for me and solved that problem, c++17 depends on the version of the compiler

Rocha answered 21/2 at 18:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.