C Programming Tutorial 34 – Increment and Decrement Operators

Did you read the last blog on Unary Plus and Minus? Are you new here? Start at the beginning, Intro to C!

Let’s say we have a variable and we want to add one to it.

The hard way to do this is to go like this:

What the assignment operator does here is take the entire expression on the right and evaluate it to a value. So pizzasToEat + 1 = 124. Then, it assigns that value to the variable on the left. So now pizza will equal 124. We can output this data before and after to see this in action.

This is pretty great if you want to add a certain amount to a variable. For example, let’s say the local pizza shop goes out of business and since I’m their biggest customer, they sell me 200 pizzas. We could do this:

If you are just adding one to a variable, there is actually a shortcut:

This operator is a unary operator because it only takes one operand, the variable. It is also unique in that it changes the value of the variable. pizzasToEat + 1 does not actually change the value of pizzasToEat unless you assign it back to the variable itself.

The ++ is called the Increment operator and it is one of the most popular operators in programming so please become familiar with it and practice using it.

Now, I’m going to introduce some trivia for you.

Let’s clean up a bit…int pizzasToEat = 100; is the only thing we have in our code.

What will this output:

5…4…3…2…1…

The answer is 100!

This is one of the trickiest things to get used to with the increment operator. We are actually saying we want the ++ to happen after the value is assigned. If we want to say increment the value before it is assigned, we put the ++ in front.

Now let’s start with int pizzasToEat = 100 again. What will this output?

5…4…3…2…1…

The answer is 101!

We can print out the value afterwards and see that I’m not lying.

There is also a decrement operator:

This is the same as doing:

These two operator are very foreign to beginners so it is often neglected. So make sure you understand what is going on in this video! If you don’t understand, keep trying examples and watch this video a few more times.

In the next blog we are going to be discussing all of the Assignment Operators. Check it out!

Leave a Reply

Your email address will not be published. Required fields are marked *