[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: GURU NEEDED : macro SQUARE(x) for any type x
From: |
Keith Thompson |
Subject: |
Re: GURU NEEDED : macro SQUARE(x) for any type x |
Date: |
Sat, 15 Jan 2011 11:55:56 -0800 |
User-agent: |
Gnus/5.13 (Gnus v5.13) Emacs/23.1 (gnu/linux) |
PKM <phoenixstormcrow@gmail.com> writes:
> On Jan 13, 11:46 pm, bolega <gnuist...@gmail.com> wrote:
>> #define SQR(x) ({typedef xtype=x; xtype xval=x; xval*xval}) // NOTE,
>> closure or {} inside () is a valid idea in C, and thus no return is
>> needed.
>
> I don't see how this could possibly work:
It can't.
It depends on two gcc-specific extensions, and it gets both of them
wrong.
Here's a version that actually works with gcc:
#define SQR(x) ({typedef typeof(x) xtype; xtype xval=(x); xval * xval;})
The "typeof" keyword is non-standard, as is the use of a "statement
expression".
There is no general solution in standard C that avoids evaluating the
argument twice.
But in practice, this:
#define SQR(x) ((x) * (x))
works perfectly well. The convention of using all-caps for macro names
warns the user that the argument might be evaluated more than once.
--
Keith Thompson (The_Other_Keith) kst-u@mib.org <http://www.ghoti.net/~kst>
Nokia
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"