variable initialization with int()

133 views Asked by At

I was trying some different ways of initializing variables.

int a(0);
cout<<a; 

for this code segment output is 0 .

in another way, I initialize a with 0

int a= int();
cout<<a;

output: 0

then I try this:

int a(int());
  cout<<a;

this time output is 1

actually what does the value the int() function return ? 0 or 1

2

There are 2 answers

7
piwi On

I think that your last attempt (int a(int())) is an example of the "most vexing parse". Thus, a is a function, not an int.

This:

#include <typeinfo>

std::cout << typeid(a).name() << std::endl;

Yields:

FiPFivEE

And putting this result here gives:

int ()(int (*)())
3
Some programmer dude On

Doing int() creates a temporary integer and value initialize it.Value initialized integers without a specific value will have the value zero. So the declaration

int a = int();

value initializes a temporary integer, and copies it to a.

However for the third example, as many have pointed out, you actually declare a function named a.