Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot use auto keyword in VS Code while coding in C++

I am using VS Code to code C++. It performs totally fine. But whenever I use auto keyword in my code, the program simply fails to Compile.

For example, to iterate over a string my code without using auto keyword will look like

#include <iostream>
#include <string>
using namespace std;
int main()
{
    string s("Hello");
    for(int i=0;i<s.length();i++)
    {
        cout<<s.at(i)<<' ';
    }
    cin.get();
}

It compiles find and runs giving Correct Output.

Executing task: g++ -g -o helloworld helloworld.cpp

Terminal will be reused by tasks, press any key to close it.

OUTPUT : H e l l o

But whenever I try to perform the same job but using auto keyword, the code looks like

#include <iostream>
#include <string>
using namespace std;
int main()
{
    string s("Hello");
    for(auto c:s)
    {
        cout<<c<<' ';
    }
    cin.get();
}

But it gives Compile Time Error

Executing task: g++ -g -o helloworld helloworld.cpp 

helloworld.cpp: In function 'int main()':
helloworld.cpp:7:14: error: 'c' does not name a type
     for(auto c:s)
              ^
helloworld.cpp:11:5: error: expected ';' before 'cin'
     cin.get();
     ^
helloworld.cpp:12:1: error: expected primary-expression before '}' token
 }
 ^
helloworld.cpp:12:1: error: expected ')' before '}' token
helloworld.cpp:12:1: error: expected primary-expression before '}' token
The terminal process terminated with exit code: 1

Terminal will be reused by tasks, press any key to close it. 

Please help me out.

like image 401
Rahul Badgujar Avatar asked Sep 20 '25 05:09

Rahul Badgujar


1 Answers

This is the clue:

Executing task: g++ -g -o helloworld helloworld.cpp

I suspect you need to compile with -std=c++11 or later.

Older builds of gcc/g++ will default to C++ 98 standard before the auto keyword was introduced. There might be other configurations where this is the default as well. The workaround is simple.

Configure your build such that the task being compiled is this:

g++ -std=c++11 -g -o helloworld helloworld.cpp 

You can also use -std=c++14 or -std=c++17 if available.

like image 200
selbie Avatar answered Sep 22 '25 20:09

selbie