Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do we need to declare functions before using them in C?

Tags:

c

c99

In C99, the compiler will issue a warning if a function is called before its declaration. For example, this will cause a warning:

int sum(const int k) {
  return accsum(k, 0);
}


int accsum(const int k, const int acc) {
  if (k == 0) {
    return acc;
  } else {
    return accsum(k-1, k + acc);
  }
}

int main() {
  int x = sum(3);
  return 0;
}

The answer I've seen after Googling is declaration is needed so that the compiler can check the parameter types to avoid errors. But why can't the compiler just go find the function definition of accsum before executing accsum when accsum is called from within sum?

like image 264
Tan Wang Avatar asked Jan 08 '23 19:01

Tan Wang


1 Answers

Actually, it is not required that a function be declared before use in C. If it encounters an attempt to call a function, the compiler will assume a variable argument list and that the function returns int.

The reason modern compilers give warnings on an attempt to call a function before seeing a declaration is that a declaration allows the compiler to check if arguments are of the expected type. Given a declaration, the compiler can issue warnings or errors if an argument does not match the specification in the function declaration. This catches a significant percentage of errors by the programmer.

As to why the compiler doesn't look ahead for a definition, there are a few contributing factors. Firstly, there is the separate compilation model of C - there is no guarantee that there will be a function definition to be found within the current compilation unit (i.e. source file). Second, it allows the compiler to work in one pass, which increases performance. Third, it does encourage the programmer to actually declare functions (e.g. in header files) which allows for reuse with a separate compilation model. Fourth, it increases the chances of a compiler actually being able to function on machines with limited memory resources.

like image 173
Rob Avatar answered Jan 13 '23 16:01

Rob