What is the difference between prefix and postfix operators?
Asked Answered
M

13

62

The following code prints a value of 9. Why? Here return(i++) will return a value of 11 and due to --i the value should be 10 itself, can anyone explain how this works?

#include<stdio.h>
main()
{
    int i= fun(10);
    printf("%d\n",--i);
}

int fun (int i)
{
    return(i++);
}
Markitamarkka answered 11/8, 2011 at 18:59 Comment(5)
return i++ will return 10. return ++i would return 11.Laryngitis
Because what is really happening are two things, first i is being returned and then i is being incremented. If you write ++i then those two things happen in the opposite order.Reich
By returning i++ an expression is created int i = i++;. Let's rewrite this as int j = i++; so it's easier to explain. This is the post-fix version of i, which means increment i after setting j = i. Because, these are primitive integers, i is deep copied to j (it's not a shallow copy, with a pointer reference), and therefore j = 10. Then i is incremented, so i = i + 1, and therefore i = 11. The pre-fix version, will increment i before it's copied to j, and therefore both variables will have the same value (j = 11, i = 11).Shellieshellproof
@tfmontague That explanation really deserves to be in an answer rather than a comment.Mauriciomaurie
Just adding a comment here, for people like myself. They also have another difference: geeksforgeeks.org/g-fact-59 , check it for the difference in priorities.Lynnelynnea
M
99

There is a big difference between postfix and prefix versions of ++.

In the prefix version (i.e., ++i), the value of i is incremented, and the value of the expression is the new value of i.

In the postfix version (i.e., i++), the value of i is incremented, but the value of the expression is the original value of i.

Let's analyze the following code line by line:

int i = 10;   // (1)
int j = ++i;  // (2)
int k = i++;  // (3)
  1. i is set to 10 (easy).
  2. Two things on this line:
    • i is incremented to 11.
    • The new value of i is copied into j. So j now equals 11.
  3. Two things on this line as well:
    • i is incremented to 12.
    • The original value of i (which is 11) is copied into k. So k now equals 11.

So after running the code, i will be 12 but both j and k will be 11.

The same stuff holds for postfix and prefix versions of --.

Mauriciomaurie answered 11/8, 2011 at 19:5 Comment(9)
@RenéG Except that i was already incremented to 11 on the previous line.Mauriciomaurie
I find it remarkable that people are still trying to edit this answer assuming I got the numbers wrong. All one has to do is run this code and print the values to see that I am correct.Mauriciomaurie
The numbers are correct, but the code isn't explained very well. For a pre-fix expression int j = ++i;, the variable i is incremented by one (i = i + 1, so i = 11), and then it's deep copied to j (so j = 11). And then for the post-fix expression int k = i++;, the variable i (which is still 11), is first deep copied to k (so k = 11), and then i is incremented by one (so i = 12).Shellieshellproof
@tfmontague Let me know if you think this is better.Mauriciomaurie
I would also add to this that the value categories of expressions differ. i++ is a prvalue expression and ++i is an lvalue expression.Kamkama
(very late response) @Kamkama As this is a C question there are no prvalues :)Mauriciomaurie
Good point! It is not a prvalue (C++ only), but rather a non-lvalue object expression (rvalue). Years ago this answer was useful to me. A mention of the different value categories (correctly labeled for C of course) might help future readers.Kamkama
For better understanding, I would switch the bullet points of 3). I would phrase it that k gets the value of i and THEN i gets incremented.Corporeal
@Corporeal I've heard it explained that way now and then, but it also leads to confusion. The fact is, ++ doesn't interact with = in any special way. So while the effect would be equivalent this particular case, it is literally backwards in terms of order of operations.Mauriciomaurie
G
18

Prefix:

int a=0;

int b=++a;          // b=1,a=1 

before assignment the value of will be incremented.

Postfix:

int a=0;
int b=a++;  // a=1,b=0 

first assign the value of 'a' to 'b' then increment the value of 'a'

Goodly answered 29/10, 2014 at 9:18 Comment(0)
L
11

The function returns before i is incremented because you are using a post-fix operator (++). At any rate, the increment of i is not global - only to respective function. If you had used a pre-fix operator, it would be 11 and then decremented to 10.

So you then return i as 10 and decrement it in the printf function, which shows 9 not 10 as you think.

Liable answered 11/8, 2011 at 19:1 Comment(0)
I
7

In fact return (i++) will only return 10.

The ++ and -- operators can be placed before or after the variable, with different effects. If they are before, then they will be processed and returned and essentially treated just like (i-1) or (i+1), but if you place the ++ or -- after the i, then the return is essentailly

return i;
i + 1;

So it will return 10 and never increment it.

Integrant answered 11/8, 2011 at 19:2 Comment(0)
T
5

There are two examples illustrates difference

int a , b , c = 0 ; 
a = ++c ; 
b = c++ ;
printf (" %d %d %d " , a , b , c++);
  • Here c has value 0 c increment by 1 then assign value 1 to a so value of a = 1 and value of c = 1
  • next statement assiagn value of c = 1 to b then increment c by 1 so value of b = 1 and value of c = 2

  • in printf statement we have c++ this mean that orginal value of c which is 2 will printed then increment c by 1 so printf statement will print 1 1 2 and value of c now is 3

you can use http://pythontutor.com/c.html

int a , b , c = 0 ; 
a = ++c ; 
b = c++ ;
printf (" %d %d %d " , a , b , ++c);
  • Here in printf statement ++c will increment value of c by 1 first then assign new value 3 to c so printf statement will print 1 1 3
Ticktock answered 23/4, 2017 at 13:45 Comment(0)
B
4

The postfix increment ++ does not increase the value of its operand until after it has been evaluated. The value of i++ is i.

The prefix decrement increases the value of its operand before it has been evaluated. The value of --i is i - 1.

Prefix increment/decrement change the value before the expression is evaluated. Postfix increment/decrement change the value after.

So, in your case, fun(10) returns 10, and printing --i prints i - 1, which is 9.

Bello answered 11/8, 2011 at 19:1 Comment(0)
G
3

i++ is post increment. The increment takes place after the value is returned.

Germayne answered 11/8, 2011 at 19:1 Comment(0)
S
3

First, note that the function parameter named i and the variable named i in main() are two different variables. I think that doesn't matter that much to the present discussion, but it's important to know.

Second, you use the postincrement operator in fun(). That means the result of the expression is the value before i is incremented; the final value 11 of i is simply discarded, and the function returns 10. The variable i back in main, being a different variable, is assigned the value 10, which you then decrement to get 9.

Satinwood answered 11/8, 2011 at 19:2 Comment(0)
W
3

Explanation:

Step 1: int fun(int); Here we declare the prototype of the function fun().

Step 2: int i = fun(10); The variable i is declared as an integer type and the result of the fun(10) will be stored in the variable i.

Step 3: int fun(int i){ return (i++); } Inside the fun() we are returning a value return(i++). It returns 10. because i++ is the post-increement operator.

Step 4: Then the control back to the main function and the value 10 is assigned to variable i.

Step 5: printf("%d\n", --i); Here --i denoted pre-increement. Hence it prints the value 9.

Wellhead answered 7/2, 2016 at 15:22 Comment(0)
T
3

Let's keep this as simple as possible.

let i = 1
console.log('A', i)    // 1
console.log('B', ++i)  // 2
console.log('C', i++)  // 2
console.log('D', i)    // 3

A) Prints the value of I.

B) First i is incremented then the console.log is run with i as it's the new value.

C) Console.log is run with i at its current value, then i will get incremented.

D) Prints the value of i.

In short, if you use the pre-shorthand i.e(++i) I will get updated before the line is executed. If you use the post-shorthand i.e(i++) the current line will run as if I had not been updated yet then i get increased so the next time your interpreter comes across i it will have been increased.

Tutto answered 29/6, 2020 at 22:18 Comment(0)
T
2

It has to do with the way the post-increment operator works. It returns the value of i and then increments the value.

Taliataliaferro answered 11/8, 2011 at 19:1 Comment(0)
P
1

fun(10) returns 10. If you want it to return 11 then you need to use ++i as opposed to i++.

int fun(int i)
{
    return ++i;
}
Pietje answered 11/8, 2011 at 19:1 Comment(0)
T
1

Actually what happens is when you use postfix i.e. i++, the initial value of i is used for returning rather than the incremented one. After this the value of i is increased by 1. And this happens with any statement that uses i++, i.e. first initial value of i is used in the expression and then it is incremented.

And the exact opposite happens in prefix. If you would have returned ++i, then the incremented value i.e. 11 is returned, which is because adding 1 is performed first and then it is returned.

Trichromat answered 14/12, 2015 at 18:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.