Petr
Petr

Reputation: 1148

Direct Initialization vs Copy Initialization for Primitives

When initializing primitive types like int or pointers one can use either copy-initialization or direct-initialization.

int a = 10;
int b(10);

Although the latter way is preffered for objects with constructors, I don't see people using it for primitives. I understand that it is kind of "more natural" (especially for numbers) to use the '=' operator but is there anybody writing things like in real-life code:

for (int i(0); i < 5; ++i) {
    cout << i << endl;
}

Thanks.

EDIT: The question asks about coding styles and best practices rather than technical implementation.

Upvotes: 5

Views: 994

Answers (4)

Antonio P&#233;rez
Antonio P&#233;rez

Reputation: 7002

I used to have a colleague doing so:

for (int i(0); i < 5; ++i) {
    cout << i << endl;
}

and it really pissed everyone off. It's far easier to read the code using i = 0 than i(0). Maybe not in this example but, as a general rule, it is.

Even for complex objects, I always prefer the i = 0 style, it just feels more natural for the reader and any decent compiler will optimize the generated code so there is virtually no performance penalty.

Upvotes: 1

dalle
dalle

Reputation: 18527

I prefer the i = 0 style, it is easier to read, and you can also use it in like this:

if (int i = some_function())
{
}

Works also fine with pointers, and all other types convertible to bool:

if (const int* p = some_function())
{
}

if (shared_ptr<const int> q = some_function())
{
}

Upvotes: 1

Bo Persson
Bo Persson

Reputation: 92391

Some people do this to be consistent.

Inside a template, the code could be

for (T i(0); i < 5; ++i) {
    cout << i << endl;
}

and writing it that way everywhere would make the coding style consistent.

Upvotes: 2

Frigo
Frigo

Reputation: 1723

Both are initialization using the copy constructor, even though the first looks like an assignment. It's just syntactic sugar.

You could check it easily with a class that prints out something at copy construction and something different at assignment.

And int being a primitive doesn't even come into play.

Upvotes: 3

Related Questions