Misdeclaring "main"
Steve Summit
scs at adam.pika.mit.edu
Sat Jul 29 14:03:24 AEST 1989
In article <2268 at auspex.auspex.com>, Guy Harris writes:
> Nope. It turned out the problem was that he'd written something like:
>
> struct foobar {
> ...
> } <<<<<<<<<<<<<NOTE: missing semicolon!
>
> main(argc, argv)
> int argc;
> char *argv[];
> {
> ...
>
> The missing semicolon caused the "struct" declaration to get glued to
> the definition of "main"... This presumably changed the calling sequence of
> "main" in such a way as to scramble the incoming arguments.
It occurred to me, the last time or so ago that this problem was
discussed, that the compiler could detect it fairly easily, by
disparaging the productions
struct { struct-decl-list } id (arg-list) decl-list compound-statement
and
struct tag { struct-decl-list } id (arg-list) ...
in favor of
struct tag id (arg-list) decl-list compound-statement
for declaring functions returning structures. That is, the
preferred way to declare a function returning a structure would
be (and is!) with a structure tag, referring to a previously-
declared structure. An attempt to declare a function within the
same declaration in which the shape of the structure was being
described would elicit an warning.
Implementation of such a feature would be straightforward: in the
structure describing a type, a bit could be kept for structure
types, recording whether the type had arisen from an explicit
structure definition, or implicitly through a structure tag.
(This bit would likely have to be kept one level of indirection
above the lowest-level structure-describing structure, since
type-equivalent structures are often stored exactly once, with
equivalence detected by pointer equality.) A function
declaration with a return type of "explicit structure" would
trigger the message.
Obviously, this warning would be appropriate for all functions,
not just those named "main." (This error is common because our
fingers aren't used to typing semicolons after close-squiggly-braces.)
If you think about it, the compiler warning I've suggested could
hardly arise accidentally (i.e. from intentionally-written code).
The production
struct { struct-decl-list } id (arg-list) decl-list compound-statement
yields a function that cannot be (correctly) called, since no
other object can be declared with a type-equivalent structure.
The production
struct tag { struct-decl-list } id (arg-list) ...
yields a function that can only be called by routines appearing
later in the same file.
Steve Summit
scs at adam.pika.mit.edu
More information about the Comp.lang.c
mailing list