Possible Duplicate:
Is there a difference in C++ between copy initialization and direct initialization?
I just started to learn C++.
To initialize a variable with a value, I came across
int a = 0;
and
int a(0);
This confuses me a lot. May I know which is the best way?
if the elements in the array are integers (int), each element in the array will be automatically initialized to 0. if the elements in the array are Strings, each element will be initialized to the null character (null). if the elements in the array are boolean, each element will be initialized to false.
The int a(0) syntax for non-class types was introduced to support uniform direct-initialization syntax for class and non-class types, which is very useful in type-independent (template) code. In non-template code the int a(0) is not needed.
Integers are whole numbers. They can be positive, negative, or zero.
Placing a 0 before number means its a octal number. For binary it is 0b , for hexadecimal it is 0x or 0X .
int a = 0;
and int a(0);
make no difference in the machine generated code. They are the same.
Following is the assembly code generated in Visual Studio
int a = 10; // mov dword ptr [a],0Ah int b(10); // mov dword ptr [b],0Ah
They're both the same, so there really is no one "best way".
I personally use
int a = 0;
because I find it more clear and it's more widely used in practice.
This applies to your code, where the type is int
. For class-types, the first is copy-initialization, whereas the other is direct-initialization, so in that case it would make a 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