S.J.
S.J.

Reputation: 133

C declarations before usage

All identifiers in C need to be declared before they are used, but I can`t find where it denoted in C99 standard.

I think it refers to macro definitions too, but there is only macro expansion order defined.

Upvotes: 2

Views: 169

Answers (2)

Michael Burr
Michael Burr

Reputation: 340446

There are a at least couple of exceptions to the rule that all identifiers need to be delcared before use:

  • while C99 removed implicit function declarations, you may still see C programs that rely, possibly unknowingly, on them. There is even the occasional question on SO that, for example, ask why functions that return double don't work (when the header that includes the declaration of the function is omitted). It seems that when compiling with pre-C99 semantics, warnings for undeclared functions are often not configured to be used or are ignored.

  • the identifier for a goto label may be used before it's 'declaration' - it is declared implicitly by its syntactic appearance (followed by a : and a statement).

The exception to the rule for goto labels is pretty much a useless nitpick, but the fact that function identifiers can be used without a declaration (pre-C99) is something that can be useful to know because you might once in a while run into a problem with it as a root cause.

Also, identifiers can be used before being 'declared' (strictly speaking, before being defined) in preprocessing, where they can be tested for being defined or not, or used in preprocessor expressions where they will evaluate to 0 if not otherwise defined.

Upvotes: 2

Christoph
Christoph

Reputation: 169773

C99:TC3 6.5.1 §2, with footnote 79 explicitly stating:

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

in conjunction with 6.2.1 §5:

Unless explicitly stated otherwise, [...] it [ie an identifier] refers to the entity in the relevant name space whose declaration is visible at the point the identifier occurs.

and §7:

[...] Any other identifier has scope that begins just after the completion of its declarator.

Upvotes: 5

Related Questions