# Prefix vs postfix increment

1. Aug 20, 2016

1. The problem statement, all variables and given/known data
i think the example is wrong ( circled part )
. I am not sure whether i posted on the correct sections or not . This is computer science homework , it should involve programming language , right ?
2. Relevant equations

3. The attempt at a solution
Because I think that it should be num is 10 , ans is 11 , right ? since it's post increment

#### Attached Files:

• ###### 23.PNG
File size:
110.4 KB
Views:
35
2. Aug 20, 2016

### Staff: Mentor

No.
The code shown is this:
Code (C):

num = 10;
ans = num++;
The value assigned to ans is 10. After that, num is incremented to 11.
For a post-increment or post-decrement operator, the variable is evaluated first and used in the assignment operation.

3. Oct 24, 2016

for the result of post-fix increment , why the value of a after increment is x = a ?
shouldnt it be x = a+ 1 ?

#### Attached Files:

• ###### 396.PNG
File size:
10.4 KB
Views:
20
4. Oct 24, 2016

### Staff: Mentor

In your attachment, x is assigned the new value of a. This leaves x and a having equal values.

5. Oct 24, 2016

why the author doesnt establish a new variable for the incremented value ? By using x , it's confusing ....

6. Oct 24, 2016

no, it's the notes.... It's stated on the top of photo in 396 , it's post-fix ..... Is the notes wrong ?

7. Oct 24, 2016

### Staff: Mentor

Because it makes compact code; needs fewer variables, and saves lines.

8. Oct 24, 2016

### Staff: Mentor

a++ and a–– is postfix ( 'post' means after)
++a and ––a is prefix ( 'pre' means before)

On this topic you need to learn both, not just one, then use whichever is appropriate when writing your own code.

If you find it confusing then you can evade using it in your own code, but you still need to be able to understand code that others have written using this notation.

9. Oct 24, 2016

### Staff: Mentor

Yes, the notes are wrong. The title of the slide is "Results of Post-fix Increment" -- it should say "Results of Pre-fix Increment". The relevant assignment is x = ++a, which is a pre-fix increment.