Re: Strange behavior with pointers

From: Bo Persson (bop_at_gmb.dk)
Date: 02/16/05


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



Relevant Pages

  • Re: Strange behavior with pointers
    ... > developed a routine to sum the four neighbors of a specific row/column ...
    (microsoft.public.dotnet.languages.vc)
  • Re: Strange behavior with pointers
    ... >> developed a routine to sum the four neighbors of a specific ... This is one possible way for the compiler to come to this result. ...
    (microsoft.public.dotnet.languages.vc)
  • Strange behavior with pointers
    ... developed a routine to sum the four neighbors of a specific row/column ...
    (microsoft.public.dotnet.languages.vc)
  • Do compilers recognize branching within fast loops
    ... Posititions of N particles in the box ... iterates over neighbors of i ... Ideally my compiler should recognize the problem, ...
    (comp.lang.fortran)
  • Re: Precision issue?
    ... >you may want to look into some sort of compensated summation algorithm. ... one should sum the numbers in order of increasing ... Optional arguments could also help a compiler optimize. ... Can someone suggest some easily generated sequences of floating point numbers ...
    (comp.lang.fortran)