1

I came across this piece of code:

#include <iostream>

int main()
{
int m = 44;
std::cout << "m = " << m << ", m++ = " << m++ << ", ++m = " << ++m <<
std::endl;

return 0;
}

My first thought was, this is undefined behavior, but it turns out this code was part of an exam in my university, so I'm not so sure now.

The question on the exam is: what is the output of this program?

I also heard that C++11 or C++14 changed the rules about UB in some way, so it might be defined now.

Anyway, the output is (on gcc in windows)

m = 46, m++ = 45, ++m = 46

Is that output correct?

parchment
  • 4,063
  • 1
  • 19
  • 30
  • clang gave me [a warning](http://melpon.org/wandbox/permlink/GIVxP3J9KeRUm0Eb). – MikeCAT Mar 16 '16 at 02:02
  • 3
    Just goes to show the quality of our higher education system. It really explains a lot of what I've been seeing, attached to the `C++` tag, for the last few years. – Sam Varshavchik Mar 16 '16 at 02:02
  • Universities are not known for their expertise in matters related to the programming profession, in my experience. – Benjamin Lindley Mar 16 '16 at 02:02
  • 3
    Yes this is undefined behaviour in all versions of C++ , although there is a proposal for C++17 which would define it with left-right evaluation order – M.M Mar 16 '16 at 02:21

0 Answers0