Date: Fri, 22 Jun 2001 08:37:04 +0200 From: Jim Segrave <jes@jes-2.demon.nl> To: questions@FreeBSD.ORG Subject: Re: What does this macro do? Message-ID: <20010622083703.A12305@jes-2.demon.nl> In-Reply-To: <bulk.53264.20010620141603@hub.freebsd.org>; from "questions-digest" on Wed 20 Jun 2001 (14:16 -0700) References: <bulk.53264.20010620141603@hub.freebsd.org>
next in thread | previous in thread | raw e-mail | index | archive | help
> > Date: Wed, 20 Jun 2001 09:49:25 -0700 > From: John Merryweather Cooper <jmcoopr@webmail.bmi.net> > Subject: Re: what does this define do? > > On 2001.06.20 09:38 j mckitrick wrote: > > > > at the risk of making a fool of myself (one which i am never hesitant to > > take ;-) could someone explain to me how this macro > > > > #define n(flags) (~(flags) & (flags)) > > > > is different from this one? > > > > #define n(flags) 0 > > > > > > Potentially, in the code generated . . . > > This is, of course, highly compiler dependent. Looks like somebody is > concerned with the efficiency of a MOV AX, 0 as opposed to an XOR AX, AX. > But IMHO, this is a waste of effort in C, since God only knows what the > compiler is going to puke out for this define. The first macro might even > result in a performance "hit" if the compiler has to make some internal > calls on the flags pseudo parameter to do bitwise operations on it. It > might be interesting (for the curious) to see how above and the following > differ in code output: > > #define n(flags) ((flags) - (flags)) > #define n(flags) ((flags) ^ (flags)) I think people are overlooking a more significant difference between: #define n(flags) (~(flags) & (flags)) and #define n(flags) 0 Not that I can see it being useful, but... If you invoke this macro with flags being a function call or (even worse), something like ++i, then the first version will generate two function calls or two increments (and undefined behaviour). Or try n(rand()) which probably won't evaluate to 0. A good compiler should see, for integer variables 'a' and 'x': a = x - x; a = x & ~x; a = x ^ x; as being reducible at compile time to zero and should generate the same code for all three, hopefully the most efficient for the target processor method of setting a to zero. The C standard does not require compilers to blindly execute every arithmetic operation in the source - it can totally delete code if the result is never used, it can evaluate constant expressions like the above at compile time and substitue the results. int increment (i) { return -- Jim Segrave jes@jes-2.demon.nl To Unsubscribe: send mail to majordomo@FreeBSD.org with "unsubscribe freebsd-questions" in the body of the message
Want to link to this message? Use this URL: <https://mail-archive.FreeBSD.org/cgi/mid.cgi?20010622083703.A12305>