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
M. Layton
  • 593
  • 5
  • 11
  • Can you compile it on the command line, or does that also produce an error? – ChrisMM Jun 20 '20 at 15:22
  • 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? – Nate Eldredge Jun 20 '20 at 15:38
  • @ChrisMM 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 ``` – M. Layton Jun 20 '20 at 15:44
  • @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 ``` – M. Layton Jun 20 '20 at 15:45
  • 4
    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. – Davis Herring Jun 20 '20 at 16:15
  • @DavisHerring c++03 would not compile `int x = {0};` – n. m. could be an AI Jun 21 '20 at 00:04
  • Are you sure this is a real compilation error and not some kind of instant syntax assistant message? – n. m. could be an AI Jun 21 '20 at 00:05
  • @n.'pronouns'm.: C++03 [does allow](https://www.godbolt.org/z/iERC9Z) that syntax ([dcl.init]/13); the braces are ignored. – Davis Herring Jun 21 '20 at 00:18
  • @DavisHerring what about `int x={};`? Anyway the compiler is based on llvm9 which is not old enough to default to c++03. – n. m. could be an AI Jun 21 '20 at 00:29
  • perhaps /usr/bin/clang++ is not the version you run from the command line? – n. m. could be an AI Jun 21 '20 at 00:41
  • @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 `=` symbol – M.M Jun 21 '20 at 09:25
  • @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) – M.M Jun 21 '20 at 09:29
  • 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... – n. m. could be an AI Jun 21 '20 at 10:26
  • solution for this problem is here https://stackoverflow.com/questions/55116344/how-to-setup-vs-code-for-c-14-c-17 – Ravi Sep 27 '21 at 14:28

4 Answers4

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
        }
      }
    ]
  }
Greg Coleson
  • 111
  • 1
  • 6
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!

Romain Simon
  • 345
  • 1
  • 7
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{ }; 
            ^
            ;
rustyhu
  • 1,912
  • 19
  • 28
  • 2
    That's not actually a Chinese character, just a [fullwidth](https://unicodeplus.com/block/FF00) semicolon... – DevSolar Aug 03 '22 at 07:35
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.