I'm very new to programming. Please help

May 16, 2016 at 9:47am
Okay I would just like to know why I'm getting this result. In my mind I should be getting something different but I can't seem to figure out where I'm going wrong.

Question:
Suppose the five C++ instructions below occur in a program. What will be the output that will be displayed on the screen?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
using namespace std;

int main ()
{
    int n;
    int m = 113;
    m--;
    n = m++;
    cout << m << " " << n << endl;

    return 0;
}


Output in my mind: 112 113
since m-- would decrease the value of m to 112
and n = m++ would give a value of 113 to variable n

Actual output: 113 112

I do apologize for this stupid question but I am stuck and don't want to continue without understanding this concept.
May 16, 2016 at 9:57am
The m++ is postincrement.
The ++m is preincrement.

The pre first modifies the value and then returns the new value.
The post returns the old value.

1
2
3
4
5
6
7
8
9
10
n = m++;
// is same as
n = m;
m = m + 1;


n = ++m;
// is same as
m = m + 1;
n = m;


A canonic way to implement postincrement for a custom type is to create a temporary for the old value, preincrement self and then return the temporary.

Some coding style guides recommend to use pre-(increment/decrement) by default and resort to post-forms only when necessary.
May 16, 2016 at 9:57am
The difference between postfix and prefix is important, however, when these operators are used in statements that do more than just incrementing or decrementing.
For example, look at the following lines:
1
2
num = 4;
cout << num++;

This cout statement is doing two things: (1) displaying the value of num , and (2) incrementing num . But which happens first? cout will display a different value if num is incremented first than if num is incremented last. The answer depends on the mode of the increment operator.

Postfix mode causes the increment to happen after the value of the variable is used in the expression. In the example, cout will display 4, then num will be incremented to 5. Prefix mode, however, causes the increment to happen first. In the following statements, num will be incremented to 5, then cout will display 5:
1
2
num = 4;
cout << ++num;


Now for your code:

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
using namespace std;

int main ()
{
    int n;
    int m = 113;
    m--; // Decrease to 112.
    n = m++; //First, it will define the n variable with 112. Then, it will increment.
    cout << m << " " << n << endl;

    return 0;
}
Last edited on May 16, 2016 at 9:59am
May 16, 2016 at 10:32am
Awesome explanation! Thanks for the quick response.
May 16, 2016 at 6:26pm
I understand everything thanks to you
May 16, 2016 at 9:02pm
It's not related to topic, but chicofeo you are awesome, I wish somebody could explain me everything just like you did!
Topic archived. No new replies allowed.