C++ Learning Resource Network!

 
 
 C++ Tutorials  >  Variables, Construct & Looping  >  Unary Operators
 

Unary operators operate on one operand(variable or constant). There are two types of unary operators- increment and decrement.

Increment Operator(++)

The increment operator(++) is a unary operator, which increments the value of a variable or constant by one. For example, to increment the value of a variable by one, the following statement can be used:

iVar = iVar + 1;

The above statement can also be written using an increment operator in the following way:

++iVar;

Prefix and Postfix Notations

The increment operator can be used in two ways- prefix and postfix. As a prefix, the operator precedes the variable. For examples:

++iVar;

As a postfix, the operator follows the variable. For examples:

iVar++;

The following code segment differentiates the two notations:

iVar1 = 10;
iVar2 = ++iVAr1;

the equivalent of this code is:

iVar1 = 10;
iVar1 = iVar1 + 1;
iVar2 = iVar1;

In this case, both iVar1 and iVar2 are set to 11 because, in the prefix notation, the increment operation is performed prior to assignment.

However, if the code is written as:

iVar1 = 10;
iVar2 = iVar1++;

the equivalent code will be:

iVar1 = 10;
iVar2 = iVar1;
iVar1 = iVar1 + 1;

Here, iVar1 is set to 11 but the value of iVar2 is 10 because, in the postfix notation, the assignment operation precedes the increment of the variable.

Decrement Operator(--)

The decrement operator(--) subtracts one from the variable. It can also be used in both prefix and postfix forms.

 
 

| Bookmark This Site |   | Links |   | Search |   | Submit |   | Contact |

  Copyright 2008 - 3008  CppTutor.com All rights reserved.