Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should an implicit declaration return an error

Tags:

c

gcc

consider the following test program

#include<stdio.h>
#include<stdlib.h>
#include <math.h>

int main()
{
   double t = nan(NULL);
   printf("%g\n",t);
   return 0;
}

compile with

/usr/local/bin/gcc  -lm -o test test.c

output is NaN as expected. However if I mistype or make a mistake and leave out the

#include <math.h>

it compiles fine, no errors, no warnings but gives the output of 0

if I compile with the -Wall it does give the warning warning: implicit declaration of function `nan' though this behaviour seems worthy of something more than a warning. Is there any point to not stopping compilation on this? and does anyone have any suggestions as to how to stop this causing a major headache on rather larger files?

like image 941
camelccc Avatar asked Sep 26 '26 22:09

camelccc


1 Answers

Should an implicit declaration return an error

Yes. Implicit declarations were "valid" (but still problematic, confusing and bad practice) in C89, but in C99 and C11, they are prohibited.

C99, 6.5.1.2:

An identifier is a primary expression, provided it has been declared as designating an object (in which case it is an lvalue) or a function (in which case it is a function designator).79

79) Thus, an undeclared identifier is a violation of the syntax.

What confuses you is that GCC and clang (given the command line switches used, I think you are using one of these) are not conforming C implementations by default, without additional strict flags such as -Werror -pedantic -pedantic-errors.


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!