Re: Strange behavior with pointers
From: Bo Persson (bop_at_gmb.dk)
Date: 02/16/05
- Next message: Mythran: "Re: Strange behavior with pointers"
- Previous message: Mythran: "Re: Strange behavior with pointers"
- In reply to: John: "Strange behavior with pointers"
- Next in thread: Doug Harrison [MVP]: "Re: Strange behavior with pointers"
- Messages sorted by: [ date ] [ thread ]
Date: Wed, 16 Feb 2005 18:24:53 +0100
"John" <John@discussions.microsoft.com> skrev i meddelandet
news:0B171982-A60E-4666-A7A6-E9E11B940F31@microsoft.com...
>I have created a program that accesses a flat 2 dimensional array and
>have
> developed a routine to sum the four neighbors of a specific row/column
> position.
>
> Here is an example, this will sum all the values of row 1, column 1
> (base 0)
> which is the number 5
>
>
> int a[9] = {1,2,3,4,5,6,7,8,9};
> int* pa = &a[3]; // row 1, column 0 (i.e. number 4)
> int n = *(pa++); // n = 4
> n += *(++pa); // n = 10 (4 + 6)
> n += *(--pa - 3); // n = 12 (10 + 2)
> n += *(pa + 3); // n = 20 (12 + 8)
>
> Now here is the strange part if I combine all the code above into one
> statement
>
> n = *(pa++) + *(++pa) + *(--pa - 3) + *(pa + 3);
>
> I don't get the same results, instead of 20 I get 18. Am I missing
> something
> here is this a compiler or programming error?
>
You cannot modify the same value (pa) more than once in each expression.
The order of evaluation is not defined in C and C++, so you cannot
predict the outcome. The compiler is allowed to do whatever it likes.
Bo Persson
- Next message: Mythran: "Re: Strange behavior with pointers"
- Previous message: Mythran: "Re: Strange behavior with pointers"
- In reply to: John: "Strange behavior with pointers"
- Next in thread: Doug Harrison [MVP]: "Re: Strange behavior with pointers"
- Messages sorted by: [ date ] [ thread ]
Relevant Pages
|