Implicit declaration in C language

Consider the following quote from a book by C by Dennis ritchie

All variables must be declared before use, although certain declarations can be made implicitly by content.

It is known that all variables of any type must be declared before use. I am not aware of the last part of the statement that some statements may be implicit in content .

In C, in general, variables fall under four basic data types: char, int, float, double. How can a variable from these datatypes be used without any declaration before. Imagine an example that shows an implicit declaration based on the content that a variable has.

+3


source to share


2 answers


By "some declarations" an author means declaring things that are not variables. At the time the book was written, C allowed for implicit declaration of functions: the compiler simply assumed that the function returned an integer. Modern C standards make such claims illegal.



+8


source


When the first edition of K&R was written, there was no C standard. When the second edition of K&R was written, the C89 / C90 standard had to be completed. Due to legacy code written before C89 was completed, the standard should have allowed:

#include <stdio.h>

double sqrt();

main(argc, argv)
    char **argv;
{
    if (argc > 1)
        printf("sqrt(%s) = %f\n", argv[1], sqrt((double)atoi(argv[1])));
    else
        printf("sqrt(%.0f) = %f\n", 2.0, sqrt(2.0));
    return 0;
}

      

Note that the return type is main()

implicit int

; function argument argc

implicitly int

; the function atoi()

has an implicit return type int

. Note also that the argument sqrt()

must be an explicitly double value; the compiler was unable to automatically convert the argument type because prototypes were not part of C until the C89 standard.



This code is no longer suitable for C99 or C11 compilers. You can use:

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

int main(int argc, char **argv)
{
    if (argc > 1)
        printf("sqrt(%s) = %f\n", argv[1], sqrt(atoi(argv[1])));
    else
        printf("sqrt(%.0f) = %f\n", 2.0, sqrt(2));
    return 0;
}

      

This uses the standard headers to declare functions with full prototypes, so you no longer need to pass an argument to sqrt()

. In C99 or C11, you can omit return 0;

and the effect will be the same. Personally, I don't like the loophole that allows this and continues to explicitly write a return. A return was needed in C90 to send a specific status to the environment (like a shell called by a program).

+2


source







All Articles