Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 707
Infinite Learner Avatar asked Dec 22 '22 19:12

Infinite Learner


1 Answers

  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.

like image 185
Zheng Qu Avatar answered Dec 25 '22 23:12

Zheng Qu