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?
Is it called a prototype in C? I’ve always known them as definitions/declarations and sometimes referred to as “headers” because they’re usually defined in header files.
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?
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.
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
I haven’t used C since 1995, but in my recollection, they’re needed so that the compiler can do type-checking (to the extent possible) in other files that use the function.
I know shit all about c, but if I were to guess I would say 1. Because to be it is defining the signature of the function.
I am an idiot though and you should disregard what I say because I do not C.
at 1 you are doing forward declaration.
you declare the interface of a function in the header file. that way the compiler would know that function
swap
exists and it takes two int pointers but returns nothing.from the outside of that module that’s all it needs to know. it can compile them separately and link them together later dynamically.
you’re separating swap interface in the header file from its implementation in the .c file that contains the body of the function.