I've seen a lot of code in textbooks and in the forums that people use the assignment operator over the initialisation one in a for
loop to start the repetition. For example,
for ( int i = 0; i < 5; ++i ) // common
for ( int i(0); i < 5; ++i ) // uncommon
I know that initialising a variable is faster than assigning it. Why do people prefer the former over the later?
Both int i = 0;
and int i(0);
declare, define and initialize an int
object with the value 0
in C++. They are strictly equivalent, so are the two loop constructs. Note that in C, int i(0);
is not an allowed construct.
Two forms of initialization you mentioned are:-
T t = u; _1
T t(u); _2
_1
This could involve two calls. One would be to conversion constructor and another would be to copy constructor.Although most compiler can elide the copy construction.
_2
This would just require only a single call to conversion constructor.
So, _2 is preferred over _1. As for built-in types, it won't make much difference.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With