Initialization of variables

Hey,

is there any difference between these three options? In java I only used the '=' one.

1
2
3
int x = 7;
int y (8);
int z {9};


The book I am reading uses {}, is this just personal preference?

EDIT: As I see now that the {} is the C++11 (standard?), so shall I go with this one?
Last edited on
in this case there is no difference.

In other cases there can be differences.

1) int x = 7; only can initialize primitive types and call non-explicit single argument constructors on class types.
2) int y (8); can call any constructor, but cannot be used everywhere.
3) int z {9}; does not allows type conversions:
1
2
int z = 9.0; //works
int z {9.0}; //does not work 
Also it works where previous one don't. On the other hand it does not work everywhere too.

Scott Meyers spent 10 pages in Effective Modern C++2014 explaining differences between them.

Last edited on
Thanks, in my beginner cases it shouldnt really make a difference then. Would you recommend anything in those cases where it doesn't matter? Is there some sort of standard then?
Pick one and adhere to it. There is no standard on that.

Even beginners can run into problems:
1
2
3
std::string foo; //Creates empty string
std::string bar{}; //Same
std::string baz(); //Surprise! It declares function without arguments returning string 

1
2
3
std::vector<int> foo(10, 20); //Creates vector with 10 element each having value of 20
std::vector<int> bar{10, 20}; //Creates vector with two elements: 10 and 20 
std::vector<int> baz({10, 20}); //Same as previous 


EDIT:
Problem with (): If there is any way for something to be parsed as function declaration, it will be.
Problem with {}: if there is any way for something braced to be threated as initialization_list, it would be.
Last edited on
Thank you for your time explaining it to me. Really appreciate it!
Topic archived. No new replies allowed.