Artie Gold <ar*******@aust in.rr.com> writes:
Keith Thompson wrote: Artie Gold <ar*******@aust in.rr.com> writes:
Keith Thompson wrote:
Artie Gold <ar*******@aust in.rr.com> writes:
[...]
>Would it have gotten that far? Seems to me it wouldn't even parse.
"return;" is perfectly legal in a function returning void. It's
a semantic error, not a syntax error.
Of course. But it's either a function returning int in C89 or nonsense
(no return type) in C99. That's what I referring to in my `wouldn't
even parse' comment.
The term "parse" refers specifically to *syntactic* analysis.
Exactly.
And and it seems to me that:
sample(k)
{
return;
}
would choke on either the `(' or the `{'.
I feel like we're arguing over the most trivial aspect of this, but ...
Parsing is based on the language grammar. The above is an old-style
definition, but let's make it explicit:
int sample(int k)
{
return;
}
The "return;" is invalid because it doesn't return a value. But this
is perfectly legal:
void sample(int k)
{
return;
}
The *parser*, when it see the "return;", doesn't remember what type
the containing function returns. The distinction between a valid
"return;" in a void function, and an invalid "return;" in an int
function, cannot be made by the parser. It can only be made during
semantic analysis.
Conceivably the grammar could have been defined with one syntax for a
void function definition (allowing "return;") and another for a
non-void function definition (disallowing "return;"). Fortunately,
this wan't necessary, since it's easy enough to detect the error
semantically.
In C99, this restriction is expressed as a constraint in 6.8.6.4p1:
A return statement with an expression shall not appear in a
function whose return type is void. A return statement without an
expression shall only appear in a function whose return type is
void.
In C90, a "return;" in a non-void function is allowed (a throwback to
K&R C, which didn't have void functions), but an attempt to use the
function result causes undefined behavior.
Incidentally, this is a distinction that the standard does not
(clearly) make. Both syntactic and semantic analysis occur during
translation phase 7. An implementation is free to mix the two in any
way it likes.
--
Keith Thompson (The_Other_Keit h)
ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.