This question comes from an attempt to understand the "C philosophy" and not from any "real problem".
Suppose that in a C program I use sin(x):
#include <stdio.h>
int main() {
char s[20] = "aha";
printf("%f", sin(s));
return 0;
}
I have deliberately made two mistakes:
- I have not
#includeed math.h (or provided any declaration for sin). - I made
sof typechar *(just something that cannot be cast meaningfully to adouble).
I compile using GCC with the -lm flag.
As expected, I get one warning and one error.
Of course, there is the warning of implicit declaration of function blah blah:
bad.c: In function ‘main’:
bad.c:5:15: warning: implicit declaration of function ‘sin’ [-Wimplicit-function-declaration]
5 | printf("%f", sin(s));
| ^~~
bad.c:5:16: warning: incompatible implicit declaration of built-in function ‘sin’
bad.c:2:1: note: include ‘<math.h>’ or provide a declaration of ‘sin’
1 | #include <stdio.h>
+++ |+#include <math.h>
A little research seems to indicate that if a function is not declared beforehand, then C assumes a "default declaration" (the so called "implicit declaration") which is like int undeclaredfunction(void).
But I also get the following error:
2 |
bad.c:5:19: error: incompatible type for argument 1 of ‘sin’
5 | printf("%f", sin(s));
| ^
| |
| char *
bad.c:5:20: note: expected ‘double’ but argument is of type ‘char *’
This shows that the "implicit declaration" expects an argument
of type double.
- It seems that C maintains a list of correct "implicit declarations" for "standard functions". Where can I find the comprehensive list of such correct implicit declarations for a given compiler (say
gccorclang)? - If C already has the correct declarations of the standard math functions built in, then why does it expect the programmer to
#include<math.h>? Just because of tradition? Or neatness?
The answer(s) that I looking for are about the exact rules used by the compiler, and not about subjective comments about "good programming practices".
int, so if you passchar*that can't be right. The compiler does not know thatsinis a double value (it could be your own function), but is does know that%finprintf()expects adoublevalue. A compiler might supply a recommendation, though, formath.h.doubleis related to the input forsin, not the output (which is supposed to be printed with%f).'sin' undefined; assuming extern returning int, and'printf' : format string '%f' requires an argument of type 'double', but variadic argument 1 has type 'int'