0

My environment is vs2013-update-5, I found my code has different result between debug and release, for example:

#include <iostream>
#include <string>
using namespace std;

int increase(int* x) {
    int previous = *x;
    *x += 1;
    return previous;
}
int main() {
    int data = 1;
    int p = 2;

    cout << ((p-data) + increase(&p)) << endl;
}

It prints 3 in debug mode and 4 in release mode. I know there's workaround like:

    int x = p-data;
    int y = increase(&p);
    cout << (x + y) << endl;

Use some temporary variable to make sure the result. But in my real case, the code is used to parse some buffer to struct, there're lots of length checking like:

if((p-data) + 4 + forward<int>(&p) != data_len) return false; 
// forward<unsigned>() increases p with sizeof(int), and return origin p
// just like the previous example 

So it's best to write with one line code, not using temporary variables.

Why is this happen? Any compile flag causes this? How to make sure the code executed in order?

aj3423
  • 2,003
  • 3
  • 32
  • 70
  • It's basically undefined behavior. – πάντα ῥεῖ Feb 07 '17 at 16:53
  • 1
    I believe this is straight up undefined behavior. The rules are a bit complicated, but essentially you must not write a variable twice or read and write a variable in the same statement. See [this](https://stackoverflow.com/questions/4968854/is-i-i-truly-a-undefined-behavior#4968880) for some details. – nwp Feb 07 '17 at 16:53

0 Answers0