Search code examples
c++initializationvariable-assignmentprimitive

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.


Solution

  • 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.