Why does this C code compile in C99? What should I read to learn more?
I can't post unless I add more text so here's some nonsense text because I don't think there's anything else to say
$ cat m.c
#include <stdio.h>
#include <time.h>
int main() {
struct timespec time;
int res = clock_gettime(CLOCK_REALTIME, &time);
printf("%d %ld %ld\n", res, time.tv_sec, time.tv_nsec);
return 0;
}
$ clang m.c && ./a.out && rm ./a.out
0 1631386905 774654955
$ clang -std=c99 m.c && ./a.out && rm ./a.out
m.c:4:18: error: variable has incomplete type 'struct timespec'
struct timespec time;
^
m.c:4:9: note: forward declaration of 'struct timespec'
struct timespec time;
^
m.c:5:12: warning: implicit declaration of function 'clock_gettime' is invalid in C99 [-Wimplicit-function-declaration]
int res = clock_gettime(CLOCK_REALTIME, &time);
^
m.c:5:26: error: use of undeclared identifier 'CLOCK_REALTIME'
int res = clock_gettime(CLOCK_REALTIME, &time);
^
1 warning and 2 errors generated.
clock_gettimeis not a part of C99, the code could be compiled either with the GNU99 extension-std=gnu99, or with the#define _POSIX_C_SOURCE 200112Lmacro<time.h>doesn't contain a declaration ofclock_gettime. Prior to C99 it was legal (though usually wrong) to use a function even if hadn't been declared; the compiler assumed an implicit declaration of the function as returningintand taking unspecified arguments. In C99 this was made undefined behavior, but GCC will still provide the older behavior after giving a warning. Anyway, you don't want any of that; the right fix is to define the feature test macro and get the proper declaration from<time.h>.