开发者

Shouldn't you always need to define functions before using them in a C file?

I have the following bit of C code:

int main() {
    myFunctionABC(2);
    return 0;
}

void myFunctionABC(int n) {
    printf("%d\n", n);
}
开发者_如何学JAVA

So... this code is working and I don't understand why. I always thought that a C compiler would always need every referred function to be already "known", otherwise would fail the compilation process.

Why is this working?


There has never been any requrement to define functions before calling them in C or in C++ (as the title of your question suggests). What is required in C++ and C99 (and in some cases in C89/90) is to declare functions before calling them.

As for your code... Your code is not "working". The best you can hope for is that your code will produce undefined behavior that will just happen to resemble "working".

Firstly, the code will not even compile as C++ or as C99 (and you tagged your question as both C and C++). C++ and C99 unconditionally require functions to be declared before they are called.

Secondly, with C89/90 compiler the code might compile, but will produce the aforementioned undefined behavior anyway. Even in C89/90 calling variadic functions (like printf) without declaring them first is illegal - it produces undefined behavior.

For non-variadic functions calling them without declaring them is OK - the implicit declaration rules of C89/90 will take care of that. But these rules will make the compiler to conclude that your undeclared myFunctionABC function returns an int, while in reality you defined it as returning void - this discrepancy leads to undefined behavior as well. Most self-respecting compilers will at least warn you about the problem.


gcc rightfully complains:

make 4356180
4356180.c:6: warning: conflicting types for ‘myFunctionABC’
4356180.c:2: note: previous implicit declaration of ‘myFunctionABC’ was here

If I add -Wall, I get these at well:

make CFLAGS=-Wall 4356180
4356180.c: In function ‘main’:
4356180.c:2: warning: implicit declaration of function ‘myFunctionABC’


It is not erroneous to declare a function prototype before actually calling it even if its definition is in a subsequent location, but it is a good practice to help the compiler out, check this similar post

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜