Re: Reverse comma operator?
On 2009-08-10, Paul N <gw7rib@aol.com> wrote:
I had an idea the other day for a new operator for C and C++, which
acts like the comma operator but which returns the first value instead
of the second.
You mean like PROG1 in Common Lisp? Quite useful indeed.
In C we have kind of a special case of this, namely post-increment. I.e.
y = x++;
is similar to a use of your $ operator:
y = x $ x++;
Implicit to a saved copy of some prior value of a computation is sometimes a
handy way to express yourself.
For example, and using $ for my operator as it doesn't
seem to be already used,
return setupstuff() , calculatevalue() $ resetstuff();
Lisp:
(progn (set-up-stuff)
(prog1 (calculate-value)
(reset-stuff)))
There is prog2 also, (but no prog3, just 1, 2 and n).
I'm pretty sure you can't emulate this operator in any way in portable C.
In the GNU C dialect, we can use the ``typeof'' operator to figure out the
return type of the expression, so that we can define a temporary variable
of a compatible type. And GNU C has block statements which return a value
(the value of the last statement in the block), similar to Lisp's PROG.
(GNU C was originally written by Lisp hackers). So in GNU C, we can easily make:
#define PROG1(A, B) ...
which evaluates A, then B, with a sequence point, and yields the value of A.
I can't think of a way to do this in ISO C. Even if we accept this ugly
interface:
#define PROG1(TYPEOF_A, A, B)
the problem is we need a block in order to be able to define the temporary
variable, which conflicts with the requirement to expand into a value-yielding
expression.
would do the same as
setupstuff();
res = calculatevalue();
resetstuff();
return res;
But you can do it like this:
(setupfstuff(), res = calculatevalue(), resetstuff(), res)
which isn't /that/ bad.
but without needing the temporary value.
I.e. the temporary variable is the /only/ inconvienience. The other aspects
of the above example are strawmen.