Skip to content

Beginner Gotchas

The Null That Picked a Port

asking for no host, and connecting to port zero

void connect(const char* host) {
  std::cout << "host: " << (host ? host : "(none)") << '\n';
}

void connect(int port) { std::cout << "port: " << port << '\n'; }

int main() {
  connect(0);
  connect(nullptr);
}

Run it. Which overload does each call reach?

Answer
port: 0
host: (none)

The call written to mean no host went to the port overload.

Why

0 is an integer literal, and connect(int) matches it exactly. Reaching connect(const char*) would need a pointer conversion, and an exact match always beats a conversion — so the pointer overload is never in contention. nullptr has type std::nullptr_t, which converts to a pointer but not to int, leaving the pointer overload as the only viable candidate. Both calls are valid, so -Wall -Wextra says nothing.

The fix

Spell a null pointer nullptr, never 0:

connect(nullptr);

NULL is not a substitute here: GCC defines it as __null, which converts to both candidates, and the call fails to compile as ambiguous.

Takeaway: 0 is an integer before it is a null pointer; write nullptr when you mean a pointer.

Try it: g++ -std=c++17 main.cpp -o demo && ./demo

Open in Compiler Explorer ↗ Quiz this entry