Forums: » Register « |  Free Tools |  User CP |  Games |  Calendar |  Members |  FAQs |  Sitemap |  Support |

New Free Tools on Dev Shed!

#1
September 9th, 2013, 12:40 AM
 Kuiva
Contributing User

Join Date: Jan 2013
Posts: 62
Time spent in forums: 1 Day 45 m 46 sec
Reputation Power: 1

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 01:24 AM. Reason: correction by SALEM, i interchanged post and pre increment

#2
September 9th, 2013, 01:13 AM
 salem
Contributed User

Join Date: Jun 2005
Posts: 4,266
Time spent in forums: 2 Months 4 Weeks 1 Day 18 h 47 m 43 sec
Reputation Power: 1827
> 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)
__________________
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
If at first you don't succeed, try writing your phone number on the exam paper

#3
September 9th, 2013, 05:34 AM
Registered User

Join Date: Aug 2013
Posts: 8
Time spent in forums: 1 h 40 m 12 sec
Reputation 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
September 10th, 2013, 11:04 AM
 Kuiva
Contributing User

Join Date: Jan 2013
Posts: 62
Time spent in forums: 1 Day 45 m 46 sec
Reputation Power: 1
thank you Shadew i get it now

 Viewing: Dev Shed Forums > Programming Languages > C Programming > Explain please, increment