In the snippet below:
#include <stdio.h>
void swap (int*, int*);
// ^----(1)
int main (void) {
int a = 21;
int b = 17;
swap(&a, &b);
printf("a = %d, b = %d\n", a, b);
return 0;
}
void swap (int *pa, int *pb) {
// ^----(2)
int t = *pa;
*pa = *pb;
*pb = t;
return;
}
Which of these between (1) and (2) can be considered as a function prototype?
1
2 is a function header followed by the opening curly brace of a function body
In case if a function prototype is not used, then what about that scenario? Is the information in the function header used?
Yes, but only if the compiler has seen it. The compiler reads from top to bottom
The function prototype serves as a function declaration. The function header + body serves as a function definition, and since all definitions are declarations, it’s also a declaration
If a function is declared but not implemented it’ll usually cause a linking error… And sometimes (with older compilers) a runtime error.
The standard here is that the declaration (1) would be in a .h file that other .c files might reference while the implementation (2) would be in a .c so it is only built once into a .o file during compilation & linking.