Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialphivosstavrou
Courses Plus Student 1,090 Pointsusing operator ++
With the following code '''C
include <stdio.h>
int main() {
// insert code here...
int a = 9;
printf("a is %d\n", a);
int c = a++;
printf("C is %d and A is %d\n", c, a);
return 0;
} '''
C should be 10 and A should be 9. In the video example as well as in Xcode i get C as 9 and A as 10. Isn't that wrong?
A's initial value is 9 and C using the a++ should have a value of 10 (9+1)
3 Answers
William O'Dell
8,831 PointsThe ++ operator runs on the variable it is being called on. Depending if it is before or after the variable it will happen before the outside check or operation.
var a = 9;
var c = ++a; //c = 10, a = 10
var d = a++; //d = 10, a = 11(after assignment)
a++; //a = 12(after assignment)
++a == 12; //false, a =13
a++ == 13; //true, a = 14 (after check)
Hope that helps.
This link goes a little more in depth about all the operators. http://www.techotopia.com/index.php/Objective-C_Operators_and_Expressions
shahardekel
20,306 PointsIf the ++ operator comes before the variable name, the variable will be incremented first, and then the assignment expression will get executed.
If the operator comes after the variable name, the assignment will get executed first, and only then the variable will be incremented.
phivosstavrou
Courses Plus Student 1,090 PointsGreat thank you guys for your help!