3

If I do this in C#

int[] arr = new int[] { 0, 1 };

fixed (int* pArr = arr)
{
    int* ppArr = pArr;
    int val = *ppArr + *++ppArr
}

I get val = 1. This I believe is the correct behavior.

If I do this in C++

int* const pArr = new int[2];
pArr[0] = 0;
pArr[1] = 1;

int* ppArr = pArr;
int val = *ppArr + *++ppArr;

I get val = 2.

Can someone explain why C++ is different? Is there a way to fix it? I am using Visual Studio 2012.

leppie
  • 115,091
  • 17
  • 196
  • 297
Elfendahl
  • 115
  • 1
  • 9
  • 2
    It is undefined behaviour in C++. You are reading from and modifying `ppArr` between sequence points. – juanchopanza Jan 27 '15 at 12:28
  • 6
    "Is there a way to fix it?" Don't write convoluted expressions that combine side effects with value computations. – Mike Seymour Jan 27 '15 at 12:29
  • 1
    In this particular case, `ppArr[0] + ppArr[1]` would be a far more readable alternative. Also, `pp` as a prefix on a variable name almost always means pointer-to-pointer (`int **`). If you've got a regular pointer-to-`int`, please don't use `pp` in code meant to be read by others. –  Jan 27 '15 at 12:36
  • @juanchopanza Thanks! I had no idea this was undefined in C++. I would mark this as the answer if I could. Also, the duplicate question http://stackoverflow.com/questions/4176328/undefined-behavior-and-sequence-points explain things quite well. Is it convoluted? Yeah, but the question was more about a difference in behavior than how to write readable code. Good thing to point out though. – Elfendahl Jan 27 '15 at 12:53

0 Answers0