0

Code 1:

#include <iostream>

int main(){
  int a = 7;
  std::cout<<++a*++a;
}

Output: 81

Code 2:

#include <iostream>

int main(){
  int a;
  std::cin>>a;
  std::cout<<++a*++a;
}

Input: 7

Output: 72

I tried using scanf() and printf() but they are also giving me different results. I compiled these on g++ 4.8.4 and DevC++ and both behave the same way. Although on ideone both give the same output 81.

Why am I getting different outputs just by getting the value as an input?

Yash Verma
  • 64
  • 1
  • 7
  • Welcome to the Undefined Behaviour. – Edgar Rokjān Jan 22 '17 at 08:19
  • @MikelF But the correct result is the first case. Even with optimization you must get 81 as result. – MRB Jan 22 '17 at 08:27
  • @MRB Undefined behaviour. There is no "correct" result. – juanchopanza Jan 22 '17 at 09:02
  • @juanchopanza Can you explain in plain word why `++a*++a` is UB? `++a * a++` is UB because the order of evaluation of parameters is unspecified, and the result depend on whether `a++` or `++a` evaluate first. – MRB Jan 22 '17 at 09:12
  • @MRB See the duplicate. It isn't just that the order of evaluation is unspecified. There is also no sequence point, so the operations can disrupt each other. But I think some of this may change in C++17. – juanchopanza Jan 22 '17 at 09:14

0 Answers0