Additional Operators

Learn about the operators that will help you change values and formulate better conditions.

We will soon write conditions and loops. In these two control structures, a few operators come handy:

  • +=, -=, *=, /=, %= etc. are abbreviations for performing a mathematical operation on a variable. a += 1 is the same as writing a = a + 1.
  • ++x increases the value of x by 1, then returns the increased value
  • x++ returns the original value of x, then increases its value by 1
  • --x decreases the value of x by 1, then returns the decreased value
  • x-- returns the original value of x, then decreases its value by 1

++x and x++

I know the difference between ++x and x++ may not make sense to you right now. I argue that in most cases, it should not even make a difference as long as you want to write readable code.

Both x++ and ++x have a main effect and a side effect. As a main effect, they return a value. Either x, or x + 1, depending on whether you write the ++ after the x or before. Basically, the difference comes because of precedence,

  • x++ executes the statement and then increments the value.

  • ++x increments the value and then executes the statement.

Get hands-on with 1400+ tech skills courses.