Wednesday 13 June 2018

C Programming for Beginners: Increment, Decrement, Prefix and Postfix Operators

This is part 5 of my series on C programming for beginners. (See also part 4)

When you want to increment or decrement by 1 (add 1 to, or subtract 1 from) the value of a variable, you may use the ++ and -- operators. Here is an example of the increment (++) operator:

int a;
a = 10;
a++; // a is now 11

This is an example of the decrement (--) operator:

int a;
a = 10;
a--; // a is now 9

PREFIX AND POSTFIX OPERATORS

You may place these operators either before or after a variable like this: a++ or ++a. When placed before a variable, the value is incremented before any assignment is made:

num1 = 10;
num2 = ++num1; // num2 = 11, num1 = 11

When placed after a variable, the assignment of the existing value is done before the variable’s value is incremented:

num1 = 10;
num2 = num1++; // num2 = 10, num1 = 11

As a general rule, I would recommend that you stick to using ++ and -- as postfix operators. In fact, there is often nothing wrong with using the longer form a = a + 1 or a = a – 1. Mixing prefix and postfix operators in your code can be confusing and may lead to hard-to-find bugs. So, whenever possible, keep it simple and keep it clear.

NOTE: If you are new to C, you may want to start with lesson 1 in this series: http://www.bitwisemag.com/2017/02/introduction-to-c-programming.html
And if you want to learn C in more depth, why not sign up to my online video course – C Programming for beginners. See here: http://www.bitwisemag.com/2017/01/learn-to-program-c-special-deal.html