Liste des Groupes | Revenir à cl c |
On 2024-12-09, Janis Papanagnou <janis_papanagnou+ng@hotmail.com> wrote:Given that the resolution is in the "semantics" section rather than the "syntax" section, it might seem like a grammatical ambiguity. But I don't think it is, technically - the syntax rules say that the set of tokens making up "if (E1) if (E2) S1 else S2" are valid syntax. It is up to the semantics to determine what the code will do here. (And the semantics are unambiguous.)An unambiguous grammar is something quite essential; how would youHere's an ambiguity in the C grammar:
parse code if it were ambiguous?
<statement>:
...
<selection-statement>
...
<selection-statement>:
...
if ( <expression> ) <statement>
if ( <expression> ) <statement> else <statement>
...
The following selection-statement is grammatically ambiguous:
if (E1) if (E2) S1 else S2
it has two possible parsings:
if (E1) <statement> else S2
where <statement> expands to
if (E2) S1
or
if (E1) <statement>
where <statement> expands to
if (E2) S1 else S2
The grammatical ambiguity is resolved by an additional rule in the
'Semantics' section for selection-statement:
3 An else is associated with the lexically nearest preceding if that is
allowed by the syntax.
gcc -Wall will issue a warning for such an ambiguous statement:gcc is not warning about ambiguity - it is well specified exactly what the code means in the language. It is warning because it might not be clear to the human reader and/or programmer.
warning: suggest explicit braces to avoid ambiguous 'else' [-Wdangling-else]
Les messages affichés proviennent d'usenet.