Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

int a = 0 and int a(0) differences [duplicate]

Tags:

c++

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?

like image 525
Psycho Donut Avatar asked Dec 06 '12 07:12

Psycho Donut


People also ask

Are ints automatically initialized to 0?

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.

What is int a 0?

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.

Is 0 an int in C?

Integers are whole numbers. They can be positive, negative, or zero.

What does 0 before number mean in C?

Placing a 0 before number means its a octal number. For binary it is 0b , for hexadecimal it is 0x or 0X .


2 Answers

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   
like image 151
SeeJay Avatar answered Sep 29 '22 19:09

SeeJay


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.

like image 29
Luchian Grigore Avatar answered Sep 29 '22 18:09

Luchian Grigore