简体   繁体   中英

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 ?

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.

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM