mdh <> writes:
> As I begin to write more little programs without the help of the
> exercises, little things pop up that I need to understand more fully.
> Thus, below, and although this is not the exact code, the principle of
> the question is the same, ( I hope
)
>
>
> #include <stdio.h>
> int i = 0;
> int main () { return 0; } /* no errors or warnings*/
>
> but
>
> #include <stdio.h>
> int i ;
> i=0;
> int main () { return 0; } /* 2 warnings. */
Others have covered most of this, but I'll jump in anyway.
``i=0;'' is a statement. A statement can appear only within a
function definition. That's not just a constraint, it's a syntax
rule, which means that violating it is likely to confuse the
compiler's parser. Since the compiler isn't expecting to see a
statement at that point, it's going to tell you something like "parse
error at line blah", or, as I just saw with gcc, "warning: data
definition has no type or storage class". It just doesn't occur to
the compiler to even try to interpret it as a statement.
This is a common problem with C: the grammar is, um, "brittle".
Syntax errors very commonly result in something that looks very much
like some *other* syntactically valid construct, especially if the
parser is designed to deal with obsolete forms. In early (pre-ANSI)
versions of C, this line:
i = 0;
outside a function was actually legal; it was equivalent to
int i = 0;
but with the type being implicit.
So, rather than treating it as a statement and then complaining that a
statement isn't allowed in that context, gcc treats it as a
declaration and then complains that it's an invalid form of
declaration because of the missing type.
As for why statements outside functions aren't allowed, consider this.
Program execution starts with a call to the function called "main".
If your "i = 0;" were allowed as a statement, when would it be
executed?
If your C compiler reports a syntax error, even in a case like this
where it doesn't call it a syntax error, it's often best to ignore the
wording of the error message, look at the line (and possibly the
previous line), figure out for yourself how you've violated the syntax
rules, fix it, and recompile. (That's a bit of an overstatement; the
error message itself *can* be meaningful.)
--
Keith Thompson (The_Other_Keith)
kst- <http://www.ghoti.net/~kst>
Nokia
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"