Abascus
Abascus

Reputation: 127

Why does the following program compile?

#include<iostream>

using namespace std;

int main()
{
    int abc();
    return 0;
}

When the compiler reaches the line int abc();, it rightly thinks that we are declaring a function named abc which does not take any arguments and whose return type is of type int. Then why is the compiler not throwing me an error because I have not defined a function named abc?

Upvotes: 2

Views: 122

Answers (2)

William J Bagshaw
William J Bagshaw

Reputation: 565

I think you have assumed the line of code is...

int a = abc();

Which would be a call to the function. (Note that this too may "compile" but will not link.)

However you have written a prototype, it is not a call to the function.

int abc();

Upvotes: 1

VLL
VLL

Reputation: 10185

It is not an error to declare a function without defining it. The function could have been defined in another file. In C++, each compilation unit (C++ file) is compiled individually, and linked together after that.

Linker does not show error either, because you don't attempt to use the function. If you attempted to use it, linker would search all compilation units for the definition, and show error when it does not find a definition.

Upvotes: 11

Related Questions