Infinite Learner
Infinite Learner

Reputation: 316

How to solve warning for variable initialization C++

I got the following warning when compiling a C++ file :

variables.cpp:10:8: warning: extended initializer lists only available with -std=c++11 or -std=gnu++11
   int c{2} ;

This is the file :

#include <iostream>
#include <string>
#include <cstdlib>
using namespace std ;

int main()
{
  int a = 0 ;
  int b(1) ;
  int c{2} ;

  string myString = "I am a string !" ;

  cout << a+b+c << endl ;
  cout << myString << endl ;

  return EXIT_SUCCESS ;
}

And this is the command line :

g++ -std=c++0x -Wall -Wextra -Winit-self -Wold-style-cast -Woverloaded-virtual -Wuninitialized -Wmissing-declarations -Winit-self -ansi -pedantic variables.cpp -o variables

I am using g++ 7.4.0 on Ubuntu 18.04.1 I do not want to ignore the warning but to solve it, Thank you

PS : I tried to change -std=c++0x to -std=c++11 but it did not change anything

Upvotes: 5

Views: 266

Answers (2)

Zheng Qu
Zheng Qu

Reputation: 798

  1. Remove -ansi in your command, which is equivalent to -std=c++98 and would overwrite your previous flag -std=c++11. According to C-Dialect-Options,

    In C mode, this is equivalent to -std=c90. In C++ mode, it is equivalent to -std=c++98.

  2. Replace -std=c++0x with -std=c++11.


Note that if your compiler supports it, it is recommended to use the lastest c++ standard which is -std=c++17. Using newer c++ standard usually makes your code shorter, more readable and more performant.

Upvotes: 11

Zig Razor
Zig Razor

Reputation: 3495

You have 2 problem in compilation command line:

The first one is the -ansi in compilation command that implicitly set the standard to the c++98. In you case the -ansi option generate conflict with -std=c++11.

The second one is the -std=c++0x, you have to replace it with -std=c++11.

Upvotes: 0

Related Questions