-5

I confused why the two identical expressions give different results? The only difference is only that in the expression () I use custom primitive wrapper types.

I'm providing code for clarity: struct Int { int value;

Int operator*(Int b) const{
    return Int{value*b.value};
}

Int operator/(Int b) const{
    return Int{value/b.value};
}

Int operator-(Int b) const{
    return Int{value - b.value};
}

const Int& operator++() {
    ++value;
    return *this;
}

Int operator--(int) {
    Int copy{value};
    value--;
    return copy;
    }
};

ostream& operator<<(ostream& out, Int x) {
    out << x.value;
}

int main(){
    int a = 11; Int A{11};
    int b = 4; Int B{4};
    cout << ++a / b * b-- - a << endl; // 0
    cout << ++A / B * B-- - A << endl; // 4
}

Also Clang compiler shows a warning -Wunsequenced but only for the expression with primitive types.

Ivan Ehreshi
  • 77
  • 1
  • 6

1 Answers1

2

All expressions like ++a / b * b-- - a have undefined behavior because variables are read from and written to without a sequence point in between.

Paul Evans
  • 27,315
  • 3
  • 37
  • 54