Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'int i = 0' vs. 'int i(0)' in a 'for' loop (assigning vs initializing the count variable)

Tags:

c++

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?

like image 297
CroCo Avatar asked Jan 02 '15 16:01

CroCo


2 Answers

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.

like image 128
ouah Avatar answered Oct 18 '22 15:10

ouah


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.

like image 32
ravi Avatar answered Oct 18 '22 15:10

ravi