0

I am trying to get use to unary operators and i found something very strange when i ran the same code in different compilers. The output was different. I used devc++ and vs-studio and both showed different outputs.

Here is my code:

#include <iostream>
using namespace std;
int main()
{
    int a, b ;
    a = 2;
    b = ++a * ++a* (a++ * a++);
    cout << b;
}

Here are the outputs of vs studio and devc++:

DEVC++ = 320

VISUAL STUDIO = 256

Talha
  • 1
  • 2
  • Not sure if this is exact duplicate, but, at least relevant: [Undefined behavior and sequence points](https://stackoverflow.com/questions/4176328/undefined-behavior-and-sequence-points) (couldn't find a better question, that would be, strictly, related to C++). Long story short: such construct invokes undefined behavior. – Algirdas Preidžius Jan 04 '21 at 12:51
  • Use `-Wsequence-point` flag in your compiler options and see the logs. `a` might be undefined – thus it's a UB. – Rohan Bari Jan 04 '21 at 12:51
  • If you do a search on SO for "increment undefined" you'll find plenty of explanations about how modifying a variable multiple times in a single statement (or without sequencing) gives undefined behaviour. – Peter Jan 04 '21 at 12:54
  • I ran your code in my pc on Visual Studio, Sublime text, Code blocks and I got 320 in every where. – Sahadat Hossain Jan 04 '21 at 12:58
  • The linked question is the wrong link - it uses the old C definition, but C++ redefined the relevant rules. See https://en.cppreference.com/w/cpp/language/eval_order for the current C++ rules. "DEVC++" is an IDE, but likely uses the outdated GCC 4.9.2 compiler. – MSalters Jan 04 '21 at 13:26

0 Answers0