Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why it's possible to invoke a function declared later in C?

Tags:

c

I have this little code to demonstrate it:

#include "stdio.h"

int main() {
    int a = testfunc();  // declared later
    printf("%d", a);
    return 0;
}

int testfunc() {
    return 1;
}

It compiles with no error, and a outputs 1 as expected.

See in action: http://ideone.com/WRF94E

Why there is no error? Is it part of the spec of C or a compiler related thing?

like image 400
xiaoyi Avatar asked Oct 16 '25 11:10

xiaoyi


2 Answers

The function testfunc() is implicitly declared. The compiler cannot do any signature checks so you might get a runtime error in case you fail to invoke it corectly.

This is part of the C specification. But the recommendation in the C specification is to declare all the functions you plan to implement and use, at the beginning of the current file or in a header file.

like image 117
Razvan Avatar answered Oct 19 '25 00:10

Razvan


Because, by default the compiler considers the undeclared functions as

int function_name ();

Internally, an undeclared function is considered with return type as int and accepts any number of arguments.It matches with your actual function also. so no issue.

like image 32
Jeyaram Avatar answered Oct 19 '25 01:10

Jeyaram