0
#include <stdio.h>
#include <stdlib.h>

int main() {
    int x = 1, y = 1;
    printf("%d\n", ++x);
    printf("%d\n", x);
    return 0;
}

This code prints out 2, 2

But in this code:

#include <stdio.h>
#include <stdlib.h>

int main() {
    int x = 1, y = 1;
    printf("%d\n", x++);
    printf("%d\n", x);
    return 0;
}

it prints out 1, 2 why should it be 2, 1 since in the 1st printf statement we first assign value of x then it is increased means it should be 2 and in the 2nd printf statement the assigned value should be printed that is 1. 2 is not assigned, why is this happening?

chqrlie
  • 131,814
  • 10
  • 121
  • 189
  • Does this answer your question? [What is the difference between ++i and i++?](https://stackoverflow.com/questions/24853/what-is-the-difference-between-i-and-i) – Ale Sep 07 '22 at 12:23
  • *"first assign value of x then it is increased"* - what do you mean by "assign value"? You aren't assigning a value to x, you are modifying it and the expression returns the old value of `x` – UnholySheep Sep 07 '22 at 12:24
  • They both increment `x`. But they are also expressions, and as such they produce a value. The difference is that `++x` evaluates to the new `x`, while `x++` evaluates to the old `x`. So `++x` is equivalent to `x += 1`, while `x++` is equivalent to `(temp = x, x += 1, temp)`. You can test it with `t = x++;` and `t = ++x;`. Both will have the same effect on `x`, but they will produce different values for `t`. – Tom Karzes Sep 07 '22 at 12:41
  • @UnholySheep may be my language is not so good but assign means value get updated or new value is stored in variable or variable value is changed. – user17651225 Sep 08 '22 at 05:49
  • What does returning value means. it may be a noobie question but i am new so i dont know very much – user17651225 Sep 08 '22 at 05:50
  • Read my comment again. It fully explains it. One more time: Try `t = x++;` and `t = ++x;` They both have the same effect on `x`, but produce different values for `t`. Expressions produce a value. In this case, `x++` produces the old value of `x` and `++x` produces the new value of `x`. Those values are then used in the value of the expression. You could also do things like `y + x++` vs. `y + ++x`. Again, both expressions will have the same effect on `x`, but different values will be added to `y`. Try it. You were given concrete examples. Run them. This should not be confusing. – Tom Karzes Sep 08 '22 at 15:54
  • @TomKarzes Ok Thanq Man i got it finally :) – user17651225 Oct 01 '22 at 07:29

0 Answers0