3

Consider this C program:

int main()
{
    puts("Hello world!");
    return 0;
}

This compiles and runs fine and as far as I understand, is legal C89. However, I'm not 100% sure about that. Compiling in C99 mode with clang informs me that implicit declaration of function 'puts' is invalid in C99 (which makes me think that the C standard must have changed in C99 to make implicit function declaration illegal, which is what I'm trying to confirm).

Is implicit function declaration legal in C89? (even if it's a bad idea to do it (unless your in an obfuscated C code challenge))

Mysticial
  • 464,885
  • 45
  • 335
  • 332
Cornstalks
  • 37,137
  • 18
  • 79
  • 144

2 Answers2

8

Is implicit function declaration legal in C89?

Yes. From section 3.3.2.2:

If the expression that precedes the parenthesized argument list in a function call consists solely of an identifier, and if no declaration is visible for this identifier, the identifier is implicitly declared exactly as if, in the innermost block containing the function call, the declaration

    extern int  identifier();

appeared.

Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680
  • 3
    In this particular case, it has well defined behavior only because `puts` happens to return an `int` results. For a non-`int` function, the behavior would be undefined. And of course it's better just to add the `#include ` anyway. – Keith Thompson Jul 07 '13 at 01:51
  • 1
    Also, using `printf()` would have invoked undefined behaviour because variable-argument list functions such as `printf()` must be appropriately declared, even in C89. Invoking them without a prototype in scope is not a good idea. – Jonathan Leffler Jul 07 '13 at 02:12
2

Implicit declaration of function is legal in C89, but is removed in C99. This can be confirmed in C11(ISO/IEC 9899:201x) standard.

In the C11 Forward section, it lists all the major changes in the third edition(i.e, C11) and the second edition(i.e, C99), one of which is:

Major changes in the second edition included:

...

— remove implicit function declaration

Also in Rationale for International Standard Programming Languages C §6.5.2.2 Function calls

A new feature of C99: The rule for implicit declaration of functions has been removed in C99. The effect is to guarantee the production of a diagnostic that will catch an additional category of programming errors. After issuing the diagnostic, an implementation may choose to assume an implicit declaration and continue translation in order to support existing programs that exploited this feature.

Community
  • 1
  • 1
Yu Hao
  • 119,891
  • 44
  • 235
  • 294