0

I recently wrote below simple program but compiler shows warning.

#include <iostream>
int main()
{
    int a();
    std::cout<<a;
    return 0;
}

[Warning] the address of 'int a()' will always evaluate as 'true' [-Waddress]

What is the meaning of the above warning? Why value of a is 1 not 0?

Destructor
  • 14,123
  • 11
  • 61
  • 126

2 Answers2

3

It might look like a definition of a as an int, but:

int a();

declares a function a taking no parameters and return int.

Use:

int a{};

instead.

std::cout<<a;

calls operator<<() with bool which is always nonzero, hence true.

Paul Evans
  • 27,315
  • 3
  • 37
  • 54
2

int a(); declares a function, not a variable. If you want a to be a zero-initialised variable, then you'll need one of

int a{};  // C++11 or later
int a = int();
int a(0);
int a = 0;

<< doesn't have an overload that can directly take a function; so it looks for a suitable conversion sequence to a type that it is overloaded for, and finds:

int() -> int(*)() -> bool

that is, using the standard function-to-pointer and pointer-to-boolean conversions. The function pointer won't be null, since a declared function must exist and have an address; so the boolean value will be true.

Mike Seymour
  • 249,747
  • 28
  • 448
  • 644