On 02/04/23 7:30 AM,
Mut...@dastardlyhq.com wrote:
> Can anyone explain the "official" explanation from whichever standard as to
> why the first assignment only compiles in C++ but not C:
Because C is not C++, and C++ is not C.
This is one of the fundamental core differences between the languages,
which is present in all potentially applicable contexts. You just
stumbled upon one of them - the `?`: operator. There are others:
* Assignment (and compound assignment) in C++ preserves lvalue-ness of
the result
int a, b = 1;
(a = b) = 2;
// Invalid in C, valid in C++
// (and starting from C++11 the behavior is well-defined)
* Prefix increment and decrement in C++ preserves lvalue-ness of the result
int i = 0;
++(++i);
// Invalid in C, valid in C++
// (and starting from C++11 the behavior is well-defined)
C language from the very beginning never cared about preserving the
lvalue-ness of expression results. In C dereference operator (unary `*`)
and its direct derivatives (e.g. `[]` and `->`) are the only operators
that produce lvalue results. Everything else produces rvalues.
C++ completely abandoned and reworked that approach. C++ does the
opposite: it goes to great lengths in order to preserve lvalue-ness of
the result whenever possible. You can see it especially well with `?:`
operator where lvalue-preservation is obviously tricky, since the types
(and value categories) of the second and third operands might not match.
The behavior of `?:` in C++ is defined by a long set of rather
convoluted rules, which depend on how well the types and categories of
the second and third operands match. This illustrates how much effort
C++ is willing to spend on preserving something that C just discarded
nonchalantly.
On can possibly argue that the rationale behind this is introduction of
reference types in C++ (and I'd say that references is just small part
of the story), but the bottom line here is that C and C++ are languages
that adhere to diametrically opposite philosophies wrt that core issue.
These are two completely different languages. The matter can only seem
surprising to those who believe in silly myths, like "C is subset of
C++" and such.
--
Best regards,
Andrey