Modern Electronics (was Re: List charter mods & headcount... ;

From: Fred Cisin <cisin_at_xenosoft.com>
Date: Wed Jun 23 20:38:21 2004

> > > > int N = 10;
> > > > while (N--) printf("%d\n",N);
> > > > What are the first and last numbers displayed?

On Wed, 23 Jun 2004, Sean 'Captain Napalm' Conner wrote:
> Precedence rules I can look up. If *I'm* in doubt, I'll add parentheses
> to make my intent clear.
I teach my students to use parentheses VERY liberally
(wheneverthere is ANY possibility of ambiguity or doubt)
but I also teach them that they will have to be able to
understand other people's code that might not have them
in places where they would be useful.

> I've been working with C for over ten years and *I* got it wrong, which I

then you don't agree with Jules that it is too trivial to consider?

But the REAL question is "how much would a book help?"

> can understand because the compiler is free to insert the increment anywhere
> between sequence points (I guess I didn't realize there was a sequence point
> in the middle there). I thought I used that form, but in going over my
> code, it looks like I've actually avoided that particular construct (while
> (var--) ... )in my code (heck, I'm looking over 10 year old code and I can't
> find that particular form).

I don't care overly much for it, but have seen it quite a bit.

> Another example to be wary of:
> i = 1;
> printf("%d %d %d\n",i++,i++,i++);
> I've seen different results from different compilers, all ANSI C
> compliant (GCC does what people expect, while the IRIX compiler followed the
> letter, if not the spirit, of the standard).

There are SOME things that K&R explicitly say are compiler
dependent or undefined, such as A[N++] = N; (sequence of lvalue v
rvalue evaluation is not defined (at least in original K&R))

> > In fact, I'd be willing to bet that 10% of the folks on this
> > list who claim to know C would get it wrong! And several of
> > those would argue about the answer without trying it.
> > (if N were to be declared "unsigned", even more would get it wrong!)
> Really? Once you realize that C treats the value of 0 as false, and
> anything else as true, then there isn't any difference between using a
> signed or unsigned int in the loop (okay, I cheated, I ran the fragment of
> code both ways---that's how I know I'm wrong).

The most common error is to think that it will start with 10,
and end with 1, but one of the other possible errors is to
somehow think that it would go past 0, and give 9 to -1.
Sharp people, who nevertheless somehow make that error, might think
that that would result in a 65535 or 2147483647, but the %d in printf
will treat the bit pattern as signed, even though the variable is
defined as unsigned.

--
Grumpy Ol' Fred     		cisin_at_xenosoft.com
Received on Wed Jun 23 2004 - 20:38:21 BST

This archive was generated by hypermail 2.3.0 : Fri Oct 10 2014 - 23:37:00 BST