Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

iOS Swift Basics (retired) Operators Unary Operators

still don't understand the ++ increment

var levelScore = 0 levelScore++ 0

var totalScore = levelScore++ 1

Why is it every time i assign the var levelScore to totalScore i get 1. But, every time i put the ++ sign before levelScore i get 2?

var totalScore = ++levelScore 2

2 Answers

Marissa Amaya
Marissa Amaya
11,782 Points

It's easier to understand if you print out the variable one right after another. It's essentially the difference between prefix and postfix.

Prefix Example:

var level_score = 0
++level_score  //equates to 1
level_score    //equates to 1

This code works as you'd expect. Adding ++ before a variable increments that variable on the same line. Thus, level_score will be executed as 1 on line 2.

Postfix Example:

var level_score = 0
level_score++  //equates to 0
level_score    //equates to 1

Here's where it gets a little confusing. Adding ++ after a variable still increments that variable, but NOT on the same line. The +1 gets added AFTER the line finishes executing. Thus, level_score will be executed as 0 on the second line, and its value will not change to 1 until line 3.

Hope that helps.

Nejc Vukovic
seal-mask
.a{fill-rule:evenodd;}techdegree
Nejc Vukovic
Full Stack JavaScript Techdegree Student 36,386 Points

HI,

well the "++" operator does a addition of 1. And it depends on the place where it is.

var levelScore = 0 levelScore++ ->0 // when the operator is behind the variable the variable value is checked before it is incremented thats why you get a 0 here. It first checks the value, returns the value of it and then increments it

var totalScore = levelScore++ -> 1 //here the value is firstly checked, incremented and then set to the totalScore variable

var totalScore = ++levelScore ->2 //here the variable totalScore is firstly incremented before the value is returned which is 2

When you get to loops this example becomes more clear.

Just notice that when the operator is before the variable that variable will the incremented before the variable is set to another or a loop checks the statement; if it's after the variable is firstly incremented and then checked.

I hope this helped a bit.