22

Possible Duplicate:
Why is it an error to use an empty set of brackets to call a constructor with no arguments?

In an answer to this question it's said that

ints are default-constructed as 0, as if you initialized them with int(). Other primitive types are initialized similarly (e.g., double(), long(), bool(), etc.).

Just while I was explaining this to a colleague of mine I made up the following code, compiled (gcc-4.3.4) and ran, and observed unexpected behavior.

#include <iostream>

int main() {
  int i(); 
  std::cout << i << std::endl; // output is 1
}

Why is the output 1 and not 0 ?

pixelgrease
  • 1,940
  • 23
  • 26
moooeeeep
  • 31,622
  • 22
  • 98
  • 187

1 Answers1

36

Most vexing parse comes into play here. You're actually declaring a function i, not an int variable. It shouldn't even compile (unless you actually have a function i defined somewhere... do you?).

To value-initialize the int, you need:

int i = int(); 
David Rodríguez - dribeas
  • 204,818
  • 23
  • 294
  • 489
Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625