Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

function declaration without definition

The following code will compile and is deterministic according to cppquiz.org (Question #30)

#include <iostream>
struct X {
  X() { std::cout << "X"; }
};

int main() { X x(); }

The output of the program is nothing, as

X x();

is a function declaration.

But still I wonder why this compiles though this declaration is never defined anywhere?

like image 890
Starhowl Avatar asked Feb 12 '23 15:02

Starhowl


2 Answers

Since x() is never called, there's nothing to link so no error from linker that it's not defined. It's only declared as a function taking no arguments and returning an X: X x();.

like image 116
Paul Evans Avatar answered Feb 16 '23 02:02

Paul Evans


X x(); itself a declaration (prototype), not a function call. If a function call is made prior to seeing its declaration then it would not compile.

like image 22
haccks Avatar answered Feb 16 '23 02:02

haccks