September 9th, 2013, 12:40 AM

Explain please, increment
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 postincrement, 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 01:24 AM.
Reason: correction by SALEM, i interchanged post and pre increment
September 9th, 2013, 01:13 AM

> int a=5+ i++; // i++ is preincrement, 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
Your explanations are wrong.
i++ is postincrement (the ++ is AFTER the variable)
++i is preincrement (the ++ is BEFORE the variable)
September 9th, 2013, 05:34 AM

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 ?
September 10th, 2013, 11:04 AM

thank you Shadew :) i get it now