This is the mail archive of the
gcc-bugs@gcc.gnu.org
mailing list for the GCC project.
Re: comma expressions with gcc 2.95.1
- To: roland dot winkler at physik dot uni-erlangen dot de (Roland Winkler)
- Subject: Re: comma expressions with gcc 2.95.1
- From: Andi Kleen <ak at muc dot de>
- Date: 31 Jan 2000 17:06:03 +0100
- cc: gcc-bugs at gcc dot gnu dot org
- References: <14485.43945.79677.639574@tfkp00.physik.uni-erlangen.de>
roland.winkler@physik.uni-erlangen.de (Roland Winkler) writes:
> Hi
>
> I wanted to have a macro `QU(x)' which gives me the square of its
> argument. And I wanted to do this in a way that the argument is
> evaluated only once. Thus my macro was based on a comma expression:
>
> static double dqarg;
> #define QU(x) (dqarg=(x), dqarg*dqarg)
>
> For an expression like `z = QU(x) + QU(y);' the expanded code is
>
> z = (dqarg = x, dqarg * dqarg)
> + (dqarg = y, dqarg * dqarg);
>
> However, using gcc-2.95.1 this piece of expanded code is evaluated
> like `z=2*x*x' and not `z=x*x+y*y', see the example program attached
> below. My system is:
Your code is buggy. It exploits undefined behaviour according to ANSI-C.
There is no sequence point between the two assignments to dparg. The
variables are only "sync"ed on sequence points. When you have two
assignments without sequence point it is undefined which value the
compiler uses.
One simple workaround is to use
static inline double QT(double v)
{
return v*v;
}
That is cleaner anyways, and will generate better code because
the compiler doesn't need to assign to a static variable.
If you are willing to use unportable gcc C extensions you could
also use
#define QP(x) ({ __typeof__(x) tmp = x; tmp*tmp; })
The inline version is probably preferable.
-Andi
--
This is like TV. I don't like TV.