Re: C and side-effects

From: Anton Altaparmakov (aia21@cam.ac.uk)
Date: Wed May 03 2000 - 18:41:01 EST


At 22:15 03/05/2000, Cesar Eduardo Barros wrote:

> while ((mm->swap_cnt << 2 * (i + 1) < max_cnt) && i++ < 10)
> /* nothing */;
>
>I'm not that good at C, mas aren't expressions with side-effects ill-defined?
>How can we be sure (short of tracking the gcc mailing lists) that i will be
>incremented after the left part of the test?

I don't know about gcc (which might be broken which I doubt), but according
to K&R, who are right by definition, the logical AND operator guarantees a
left-to-right evaluation of its operands. Also, the second operand is only
evaluated if the first operand is not equal to 0. (If it equals zero the
value of the expression is 0 and the second operand is not evaluated at all.)

Hence there is no ambiguity in the code; i will only be incremented after
the first operand is evaluated to be non-zero, and only after the second
operand has been evaluated, too for that matter.

>I'd suggest
> while (mm->swap_cnt << 2 * (i + 1) < max_cnt)
> {
> int j = i++;
> if (!(j < 10))
> break;
> }

This looks unnecessarily complicated! - Why do you need to use an
additional local var j? It is much simpler and functionally equivalent to do:

         while (mm->swap_cnt << 2 * (i + 1) < max_cnt)
                 if (i++ >= 10)
                         break;

But as I said above, the original statement is just fine and completely
unambiguous.

If you are having problems with knowing this kind of stuff I suggest you
(re-) read K&R[1].

Just my 2p.

         Anton

[1] Kernighan & Ritchie, The C Programming Language, 2nd Ed. This book is a
must have if you want to write C programs, IMO.

--

"Education is what remains after one has forgotten everything he learned in school." - Albert Einstein

-- Anton Altaparmakov Voice: 01223-333541(lab) / 07712-632205(mobile) Christ's College eMail: AntonA@bigfoot.com Cambridge CB2 3BU ICQ: 8561279 United Kingdom WWW: http://www-stu.christs.cam.ac.uk/~aia21/

- To unsubscribe from this list: send the line "unsubscribe linux-kernel" in the body of a message to majordomo@vger.rutgers.edu Please read the FAQ at http://www.tux.org/lkml/



This archive was generated by hypermail 2b29 : Sun May 07 2000 - 21:00:13 EST