Re: ++i vs i++
From: Malcolm (malcolm_at_55bank.freeserve.co.uk)
Date: 09/30/04
- Next message: Dan Pop: "Re: Is this valid C statement?"
- Previous message: Dan Pop: "Re: OT: Re: fopen() vs. open()"
- Next in thread: John Bode: "Re: ++i vs i++"
- Reply: John Bode: "Re: ++i vs i++"
- Maybe reply: Dave Thompson: "Re: ++i vs i++"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Date: Thu, 30 Sep 2004 20:47:52 +0100
"John Bode" <john_bode@my-deja.com> wrote
>
> Didn't you just say that evidence isn't proof?
>
> This is priceless. The bug had *** all to do with the preincrement
> operator; like Michael pointed out, the same UB would have shown up if
> I hadn't used the preincrement. The root cause of the bug is that C
> arrays are 0-origin (and that I wasn't paying close enough attention).
>
Here's the code
added by Malcolm
int stack[STACK_SIZE];
int sp;
> if (sp < STACK_SIZE)
> {
> /*
> ** The following statement replaces these two statements
> **
> ** sp = sp + 1;
> ** stack[sp] = value;
> */
> stack[++sp] = value;
> }
> else
> {
> /* handle overflow */
> }
>
Seems to me quite clearly that the pre-increment is contributing to the
problem. On entry, sp < STACK_SIZE, so writing "stack[sp++] = value;" would
give you the right behaviour, at the price of making sp no longer pointing
to stack top but to the empty space above it.
>
> > However programmers make errors all of the time.
>
However we all make mistakes, so to conclude that pre-increment is confusing
on the basis of one bug is a bit premature. To conclude that it is not
confusing (evidence isn't proof, therefore evidence that falls short of
proof is evidence against) is a fallacy.
>
> The maximum stack size is a *logical* entity; there's no reason why
> the physical implementation has to be the same size. In fact, the way
> I wrote it, the array *has* to be STACK_SIZE+1 elements to hold
> STACK_SIZE items, because element 0 is never written to.
>
You're in good company here. No less than the authors of "Numerical Recipies
in C" endorse 1-based arrays. Mathematicians count 1, 2, 3 ..., computers
count 0, 1, 2 ... . However the consensus is that 1-based arrays in C are a
bad idea.
- Next message: Dan Pop: "Re: Is this valid C statement?"
- Previous message: Dan Pop: "Re: OT: Re: fopen() vs. open()"
- Next in thread: John Bode: "Re: ++i vs i++"
- Reply: John Bode: "Re: ++i vs i++"
- Maybe reply: Dave Thompson: "Re: ++i vs i++"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]