0
#include <iostream>
using namespace std;
int main() {
    int x, y;
    cin >> x >> y;
    x = x + ++y % x;
    y = --x / y + x * y;
    cout<< "x= " << x << endl;
    cout << "y= " << y << endl;
        return 0;
}

let the inputs be x=6 and y=8

How is x = 8 and not 9 and how is y=72 not 73

How I calculated it:

x=6+ 9mod(6)=9

y=((9-1)/8)+9*8=73

what did I do wrong here ??

  • 3
    `y = --x / y + x * y;` is arguably hostile code. Which `x` should be evaluated first? – Drew Dormann Jan 24 '22 at 22:32
  • 3
    TL;DR of the dupe: Do not modify the variable you are using as part of an expression. – NathanOliver Jan 24 '22 at 22:33
  • You may want to read about sequence points: https://stackoverflow.com/questions/4176328/undefined-behavior-and-sequence-points – tomaszmi Jan 24 '22 at 22:33
  • @DrewDormann Not just arguably. Overtly. – Paul Sanders Jan 24 '22 at 22:45
  • @PaulSanders Undefined behaviour means any outcome is possible. No observable symptoms (i.e. the code behaves as a programmer expects, at least during the testing that programmer does) and covert hostility are also potential consequences. – Peter Jan 24 '22 at 22:52
  • 1
    If you want that first value to be `(9-1)` write it that way. Your future self will thank you. – Pete Becker Jan 24 '22 at 22:56
  • "Everyone knows that debugging is twice as hard as writing a program in the first place. So if you're as clever as you can be when you write it, how will you ever debug it?" -Brian Kernighan. – user4581301 Jan 24 '22 at 22:58
  • @DrewDormann isn't there a certain order of operations? – PoliceProgrammer Jan 24 '22 at 23:11
  • @PoliceProgrammer the compiler warnings that I've turned on [say no](https://godbolt.org/z/a3oh4aqY5). However, some might say that no reasonable programmer should write `--x / y + x * y`, or any code that could be interpreted multiple ways. – Drew Dormann Jan 24 '22 at 23:14
  • C++ is not a nanny language. It gives you enough rope to shoot yourself in the foot. – Eljay Jan 24 '22 at 23:43
  • Takes real skill to shoot yourself with a rope. – user4581301 Jan 25 '22 at 00:58

0 Answers0