This is the mail archive of the gcc-bugs@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]

Re: comma expressions with gcc 2.95.1


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.

Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]