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 trial

iOS Objective-C Basics (Retired) Fundamentals of C Operators and Expressions

How come both variables need to be printed to cause increment?

If I type:

int a = 1
printf("a %d", a);
int b = a++
printf("b %d", b);

it comes out printing 1 both times, but if I enter:

printf("a %d b %b", a, b)

i get a 1 b 2

1 Answer

J.D. Sandifer
J.D. Sandifer
18,813 Points

Are you sure you don't mean "i get a 2 b 1"?

The ++ operator can be either before the variable (auto increment) or after (increment). The difference is when the variable is incremented by 1 - before or after any operations on the same line.

Here's a play by play of the code:

int a = 1;           // a equals 1
printf("a %d", a);   // prints "a 1"
int b = a++;         // b equals 1, *after that* a is incremented to 2
printf("b %d", b);   // prints "b 1"

printf("a %d b %d", a, b);
                     // if you add this line it reads "a 2 b 1"