comp.lang.c
[Top] [All Lists]

Re: ?: as an lvalue

Subject: Re: ?: as an lvalue
From: Andrey Tarasevich
Date: Mon, 31 Mar 2008 13:44:34 -0700
Newsgroups: comp.lang.c


Richard wrote:
Exactly why a?b:c can't appear like that on the left-hand-side of an assignment is a bit of a mystery; after all a, a.b, a->b, a[b] and so on can all appear on the lhs without the programmer having to insert explicit address-of operators.
Because b and c are two distinct objects that can have different types,
which makes the type of any resulting lvalue somewhat problematic.

That should nail it ...

No, that completely misses it. For example, what will happen if you try to compile this

  double* d;
  int* i;

  1 < 0 ? d : i;

Here's another example

  struct A { int i; } a;
  struct B { int i; } b;

  1 < 0 ? a : b;

I'll answer it for you: in both cases the code is invalid. It won't compile. Why? Because the existing type-compatibility requirements imposed on the second and third parameter of '?:' have been violated. Note, that this is normal C '?:', which returns a non-lvalue. Did that little "non-lvalue" detail somehow help it to compile in the above example? No, it didn't.

What it illustrates is that the type-compatibility requirements are _already_ in the language. They are already there and there's no way around them. The fact that '?:' returns a non-lvalue in C doesn't really make things easier. And making '?:' return an lvalue wouldn't really make things harder.

(And, once again, this is a purely academic argument for me. I'm not trying to campaign for lvalue-returning '?:')

--
Best regards,
Andrey Tarasevich

<Prev in Thread] Current Thread [Next in Thread>
Privacy Policy