0

I've recently started to learn c++ and while I was testing myself with possible interview questions, I've ran into that chunk of code:

#include <iostream>

void F(int& y, int& x) {
    std::cout << x++ << --y;
}

void main() {
    int a = 5;
    F(a, a);
    std::cout << a;
}

And the output is:

455

So I do know that preincrement is faster than postincrement, but why if we swap arguments like:

...
std::cout << --y << x++;
...

the output suddenly changes to

555
NathanOliver
  • 171,901
  • 28
  • 288
  • 402
Ray
  • 1
  • 1
  • 2
    "preincrement is faster than postincrement," no, you can't conclude that. You can only conclude that the decrement executed before the increment – Mooing Duck Dec 02 '20 at 19:54
  • 3
    What version of C++ are you using? This behavior has changed recently. – NathanOliver Dec 02 '20 at 19:54
  • 2
    Dupe https://stackoverflow.com/questions/2129230/cout-order-of-call-to-functions-it-prints This could be added to the target list as well https://stackoverflow.com/questions/38501587 – cigien Dec 02 '20 at 19:56
  • @NathanOliver I am using Visual Studio 2019 16.7.5 with default C++ standart (not sure which one is set by default in there). – Ray Dec 02 '20 at 20:08
  • 1
    By default, VS2019 defaults to C++14 mode. If you switch it to C++17 mode, you'll get the "expected" behavior. – NathanOliver Dec 02 '20 at 20:10
  • @NathanOliver hm, right, it does work as expected. Do you know what causes that unexpected behaviour in previous standarts? – Ray Dec 02 '20 at 20:12
  • See the duplicate, all is explained there. – NathanOliver Dec 02 '20 at 20:13
  • @NathanOliver Currently reading it. Thanks! – Ray Dec 02 '20 at 20:16
  • @MooingDuck Can you edit the target list please? The current target is for C. While the answers may be relevant, there are better C++ targets that I listed in my comment. – cigien Dec 02 '20 at 20:54
  • @cigien I did not know that was an option! Fixed! – Mooing Duck Dec 02 '20 at 22:11
  • @MooingDuck Oh, yes, it's a very nice feature. If you have a gold tag badge, you can edit the target lists if they're wrong, or add additional targets as you feel appropriate :) – cigien Dec 02 '20 at 22:20

0 Answers0