Generally accepted syntax for assigning values to variables

Hello again.

I have a question in regards to what is the generally accepted syntax assigning values to a variable. I have learned that there are two ways to do so:
1
2
int a = 0;
int b(1);


In class I have only seen the first method taught, and the second method is only mentioned in C++ books I have read outside of class. Is one method generally preferred over the other, or is it just personal preference? Is there really any difference other than syntax between the two methods of assigning a value to a variable?
closed account (zb0S216C)
Both examples are the same except that the second example calls the type constructor. Personally, I always call the type's constructor( at the point of definition ).
The first one calls the constructor too. They're equivalent.
It's just a matter of style and yes, the first one is more commonly used.

However, as soon as the constructor has more than one parameter, you can no longer use the first variant.
Last edited on
Thanks for the responses.

Would it be possible to use the second assignment method away from the declaration statement? For example:
1
2
3
int a(0), b(0);
// Some code manipulating variable a...
b(a);
Nope, you can't call the constructor again on an object that already has been constructed (an analogy could be: you can't be born again if you've already been born).
You'll have to use b=a, although you should be aware that even though it looks like the first variant, this is actually a call to operator= and not to a constructor.
Last edited on
closed account (zb0S216C)
Would it be possible to use the second assignment method away from the declaration statement?

No, unless you did this:
1
2
int Var( 0 );
Var = int( 7 );
Thanks again. I didn't think it would be possible to use the second constructor method after the initial declaration, but figured I would ask and make sure.

It is always fascinating to find different ways to achieve the same result, and hopefully I will continue to do so.
Topic archived. No new replies allowed.