Declaring varibles

My teacher asked why I declare my varibles like:
int x(0) and I told him I liked the way it looked over int x = 0. He told me it was good I did it this way and explain to the class why.
I tried to search for why that's better but was unable to come up with anything but a name.

My question is what are the pros and cons of declaring a variable like int x(0) vs int x = 0?
Last edited on
1
2
3
4
int x; // declaring
x = 0; // initializing EDIT: Assignment statement

int x = 0; // declaring and initializing in one line 
Last edited on
My question is what are the pros and cons of declaring a variable like int x(0) vs int x = 0?

There is absolutely no difference. Both assign the value 0 to x.
@Arslan7041: your line is not initialization.
1
2
3
4
5
int x; // declaring

x = 0; // assignment to existing variable

int x = 0; // declaring and initializing 


@BMW330i: you have only two forms. There are more:
http://www.informit.com/articles/article.aspx?p=1852519


The parentheses are involved in "the most vexing parse":
https://en.wikipedia.org/wiki/Most_vexing_parse

Then again, like in Arslan7041's post, people tend to confuse assignment (=) and initialization (=). Yes, the same character = in different contexts is a different thing. Oh, and the mistyped equality operator ...

Matters of style.
int x(0)

Is a direct initialization, it is an explicit call of constructor.

int x = 0

Is a copy initialization, it is an implicit call of constructor, it involves extra copying and moving than the direct method. Compilers usually optimize a copy initialization to a direct one, but the only way to be sure is to do it by yourself.

Extra info:

http://stackoverflow.com/questions/1051379/is-there-a-difference-in-c-between-copy-initialization-and-direct-initializati

http://stackoverflow.com/questions/4470553/initialization-parenthesis-vs-equals-sign

Last edited on
closed account (LA48b7Xj)

int x(0)

Is a direct initialization.

int x = 0

Is a copy initialization, it involves extra copying and moving than the direct method. Compilers usually optimize a copy initialization to a direct one, but the only way to be sure is to do it by yourself.


Are you sure?, I thought they both just call the constructor and are both equivalent.

Also...

int x{0};

is better if you are using a modern compiler than

int x(0);

Because initialization using {} does not allow narrowing.
@Keskivertso: Oops! How embarrassing. Fixed it, thanks.
Thank You everyone!
Topic archived. No new replies allowed.