1

Is it necessary to declare a variable before using it if the compilation works anyway ?

/* hello-world.c */

#include <stdio.h>

int main(void) {
    printf("Hello World!\n");
    printf("1 + 2 is: %d\n", sum(1, 2));

    return 0;
}
/* sum.c */
int sum(int a, int b) {
    return a + b;
}

I compile these code with gcc hello-world.c sum.c and clang hello-world.c sum.c, both got a warning: implicit declaration of function 'sum' but compiled the a.out.

Is there any case proving it's absolutely necessary to declare before using in C?

(edit: Here, i mean the function prototype, if there is any confusion)

js100cc
  • 57
  • 5

2 Answers2

1

"proving" with C is done by the C Standard, not by observation of compilers. Because the standard leaves a lot of things up to compiler discretion .

This program was valid in C89 but is not valid in C99 and later (in which undeclared identifiers cannot be used in expressions).

What the compiler chooses to do with non-compliant programs is up to that compiler, except that some violations (including this one) must result in a diagnostic being printed. Perhaps your compiler opts to print the diagnostic and then go on to behave like C89 .

M.M
  • 138,810
  • 21
  • 208
  • 365
0

The classical case is incompatible implicit declaration:

// a.c
int f()
{
    return g();
}

// b.c
float g() { return 3.14; }

In this case, it is undefined behavior.

Daniel
  • 30,896
  • 18
  • 85
  • 139