Home > Software engineering >  C incorrect output
C incorrect output

Time:11-04

I wrote simple program on C

#include<iostream>
using namespace std; 

int main() {
    int   number19 , number20  ;
    const int number = 10 ;
    number20 = number   10 ;
    number19 = number20--;
    cout << number << endl;
    cout << number20 << endl;
    cout << number19 << endl;
    return 0;
}

I think that output should be: 10 20 19 But output is 10 19 20

Why I get such output ?

CodePudding user response:

There is a rather large difference between pre- and post-increment and decrement.

The pre-decrement returns the new value, while post-decrement returns the old value.

That means you statement

number19 = number20--;

is really equivalent to something like:

{
    int old_number20 = number20;
    number20 = number20 - 1;

    number19 = old_number20;
}

Any decent beginners learning resource should have had that information.

CodePudding user response:

Basically you need to understand how the decrement operators work.

number19 = number20--;

is doing something different than

number19 = number20 - 1;

where the latter seems to be what you expect.

Briefly number20-- is an expression that actually changes the value of the variable number20 but evaluates to the original value whereas number20 - 1 is an expression that just returns the value of the expression without touching the variable.

There is also another form of decrement, --number20, that will change the value of the variable and evaluate to the new value.

  • Related