(a ? b : c = 0) is parsed as ((a ? b : c) = 0) in D,
but as (a ? b : (c = 0)) in C and C++.
Comment #1 by ag0aep6g — 2015-02-16T11:27:39Z
I'm not well-versed in C/C++, but according to these pages:
http://www.gnu.org/software/gnu-c-manual/gnu-c-manual.html#Operator-Precedence (points 13 and 14)
http://en.cppreference.com/w/cpp/language/operator_precedence#content (point 15)
it's C++ that deviated from C. Whereas D is line with C.
A little test with gcc and g++ seems to confirm that:
----
#include <stdio.h>
int main()
{
int b = 1, c = 1;
1 ? b : c = 0;
printf("%d\n", b);
return 0;
}
----
Compiling with gcc gives
----
test.c: In function ‘main’:
test.c:5:15: error: lvalue required as left operand of assignment
1 ? b : c = 0;
^
----
Compiling with g++ succeeds, and running prints "1".
Comment #2 by dfj1esp02 — 2015-02-16T12:15:22Z
Interesting, C99 and C11 don't allow for that:
assignment-expression:
conditional-expression
unary-expression assignment-operator assignment-expression
i.e. same precedence right-to-left associative.
Comment #3 by dfj1esp02 — 2015-02-16T12:28:26Z
Can you confirm it with --std=c99 -pedantic?
Comment #4 by ag0aep6g — 2015-02-16T12:44:10Z
(In reply to Sobirari Muhomori from comment #3)
> Can you confirm it with --std=c99 -pedantic?
Same error:
----
$ gcc --std=c99 -pedantic test.c
test.c: In function ‘main’:
test.c:5:15: error: lvalue required as left operand of assignment
1 ? b : c = 0;
^
$ gcc --version
gcc (Ubuntu 4.9.1-16ubuntu6) 4.9.1
----
(In reply to Sobirari Muhomori from comment #5)
> Looks like gcc has some history under this issue:
> https://gcc.gnu.org/bugzilla/show_bug.cgi?id=6905
That ticket is about C++ though. But if C99 changed/clarified the operator precedence, gcc seems to be buggy in that regard.
For D that raises the question what version of C we're aiming for. K&R C, contemporary ANSI C, C as popular compilers understand it, ...?
Comment #7 by yebblies — 2015-03-25T12:35:00Z
A better option might be to make it a parse error, like we did with a < b < c.
Comment #8 by nick — 2018-10-15T09:06:50Z
(In reply to ag0aep6g from comment #1)
> int b = 1, c = 1;
> 1 ? b : c = 0;
The quoted code is now deprecated:
Deprecation: `1 ? b : c` must be surrounded by parentheses when next to operator `=`
*** This issue has been marked as a duplicate of issue 18743 ***