-5

I would expect that the two conditionals would yield the same answer (nEntries = 0). I don't understand why it doesn't.

# include <stdlib.h>
# include <iomanip>
# include <iostream>

using namespace std;

    int main() {
       int nEntries = 1;
       nEntries = (nEntries)? nEntries--: nEntries;
       cout << "nEntries = " << nEntries << endl;   // nEntries = 1
       nEntries = 1;
       if (nEntries) nEntries--;                    // nEntries = 0
       cout << "nEntries = " << nEntries << endl;
       return 0;
}

It looks like the conditional expression is doing:

if (nEntries) tmp = nEntries--;

art

lostbits
  • 928
  • 1
  • 9
  • 23

1 Answers1

4
nEntries = (nEntries)? nEntries--: nEntries; // statement 1
// ...
if (nEntries) nEntries--;  // statement 2

1 and 2 are not equivalent statements, so there is no reason to expect them to behave equivalently.

// statement 3, equivalent with statement 1
if (nEntries)
     nEntries = nEntries--; // Assignment and decrement are unsequenced modifications.
                            // The behaviour is undefined.
else
     nEntries = nEntries; // this is pointless...

As you can see, statement 1 and it's equivalent 3 have undefined behaviour, so you cannot expect it to behave in any particular way.

In case you aren't familiar with unsequenced modification being undefined, see Undefined behavior and sequence points

Community
  • 1
  • 1
eerorika
  • 232,697
  • 12
  • 197
  • 326
  • Thanks for the answer. I am unfamiliar with unsequenced behavior and will attempt to get smarter. Thanks. – lostbits Sep 27 '15 at 22:46