1. No Profile Picture
Contributing User
Devshed Newbie (0 - 499 posts)

Join Date
Jan 2013
Posts
76
Rep Power
3

Code:
```#include <stdio.h>

main()
{
int i=1;
int a=5+ i++;
int b=a*++i;

printf("%d", b);
getch();
}```
this is my simulation:

int i=1; // i initialized to 1
int a=5+ i++; // i++ is post-increment, therefore, 5+1=6
int b=a*++i; // value of a which is 6 transferred to b, then ++i is pre increment, therefore the value is 2, 6*2=12

when i run the program, the answer is: 18

my question is how did ++i in int b became 3 when it was initialized to value 1, shouldn't that be 2 instead?
Last edited by Kuiva; September 9th, 2013 at 12:24 AM. Reason: correction by SALEM, i interchanged post and pre increment
2. > int a=5+ i++; // i++ is pre-increment, therefore, 5+1=6
> int b=a*++i; // value of a which is 6 transferred to b, then ++i is post increment, therefore the value is 2, 6*2=12
i++ is post-increment (the ++ is AFTER the variable)
++i is pre-increment (the ++ is BEFORE the variable)
3. No Profile Picture
Registered User
Devshed Newbie (0 - 499 posts)

Join Date
Aug 2013
Posts
8
Rep Power
0
Hello,

Here is the state of your data :

int i=1;

int a=5+ i++;
a = 5 +1;
a = 6 ; i = 2 (i++ increments i and returns the old value)

int b=a*++i;
b = 6*3; (++i increments i and returns the new value)
b = 18; a = 6; i = 3.

Do you understand now ?
4. No Profile Picture
Contributing User
Devshed Newbie (0 - 499 posts)

Join Date
Jan 2013
Posts
76
Rep Power
3
thank you Shadew :) i get it now