-2

I have a non important question about compilers for C++. The following code outputs

1
2
3

and I can't figure out why. What difference does declaring it with empty parameters make to no parenthesis at all?

#include <iostream>
using namespace std;

int main()
{
    int x;
    cout << x << endl;

    int y();
    cout << y << endl;

    int z(2);
    cout << z << endl;

    return 0;
}

The compiler is g++.

songyuanyao
  • 169,198
  • 16
  • 310
  • 405
Dalinar42
  • 36
  • 3

1 Answers1

4

The 1st one, x is default initialized with indeterminate value, then cout << x leads to undefined behavior, means anything is possible.

Default initialization of non-class variables with automatic and dynamic storage duration produces objects with indeterminate values

The 2nd one, int y(); declares a function named y, which has no argument and returns int. For cout << y, y will decay to function pointer, which could convert to bool implicitly and then you'll get 1 (i.e. true. You can use std::boolalpha like std::cout << std::boolalpha << y to get the output true).

The 3rd one, z is direct initialized with value 2, then cout << z you'll get 2.

LIVE sample with clang, note all the warning messages the compiler gives.

songyuanyao
  • 169,198
  • 16
  • 310
  • 405
  • `int y()` is **not** an example of the most vexing parse. It’s not mentioned on the page you link to; the examples there involve attempts to call functions using arguments that end up being parsed as types. That’s not what’s involved with `int y();`. – Pete Becker Nov 14 '18 at 03:38