Reputation: 53
1. int main(void)
2. {
3. int a =5, b = 6, c;
4. a + b = c; // lvalue required error
5. 2 = a ; //lvalue required error
6. }
4th and 5th lines of code are considered as a syntax error or semantic error? According to me, these lines should throw the syntax error but I found that Context Free Grammar can generate them.
Upvotes: 1
Views: 703
Reputation: 133929
As you said it, it is a semantic error / constraints violation.
From C11 6.5.16p2
Constraints
- An assignment operator shall have a modifiable lvalue as its left operand.
The C syntax description is not enough to discern lvalues from non-lvalues.
The actual production where the assignment operator appears is C11 6.5.16p1:
unary-expression assignment-operator assignment-expression
And unary-expression
includes, among everything else, the possibility of having any expression in parentheses.
So a simple parser following the grammar indeed is going to generate proper parse trees for these invalid expressions, and further analysis is required to see whether or not they match the constraints in the standard.
Even the simplest cases, like
foo = 5;
might or might not be valid - depending on whether or not foo
is a modifiable lvalue and whether 5
is assignable to a modifiable value of type of foo
without a cast...
HOWEVER, there is this one small thing. The production
unary-expression assignment-operator assignment-expression
allows only an unary exception on the left-hand side. It does not allow for a + b
to appear on LHS unparenthesized! There seems to be something fishy going on with all the C compilers I've tried (GCC, MSVC, clang). It can be that all of them use the C++ grammar and then weed out the impossibilities. In C++,
a + b
could return a mutable reference, and hence should be allowed to appear on the left-hand side.
Upvotes: 6