Page 37 - Modular_V2.0_C++_Flikpbook
P. 37
Increment and Decrement Operators
C++ provides increment (++) and decrement (– –) operators which are used to increase or
decrease the value of a variable by 1. These are called unary operators because they operate on
a single operand. For example:
a = 10;
a = ++a; // means a = a + 1
a = --a; // means a = a - 1
C++ allows you to use these operators in two ways:
Prefix (++a or --a): The operator is placed before the operand.
Postfix (a++ or a--): The operator is placed after the operand.
The difference between prefix and postfix (++ and – –) operators is that, in case of prefix operators
the value of the variable is incremented/decremented first and then the expression is evaluated.
In case of postfix operators, the expression is evaluated first and then the value of the variable is
incremented/decremented. Consider the preceding example:
int a = 10, b = 0;
b = ++a; //Prefix increment: a is incremented first, then assigned to b.
b = a++; // Postfix increment: a is assigned to b first, then incremented.
b = --a; // Prefix decrement: a is decremented first, then assigned to
b.
b = a--; // Postfix decrement: a is assigned to b first, then decremented.
Program 6: To use prefix increment/decrement operators.
#include<iostream.h> DOSBox 0.74, Cpu speed: max 100% cycles, Frames 0, Program:
The old value of a is: 10
#include<conio.h>
The value of a after prefix increment is: 11
void main() The value of b is: 11
{ The value of a after prefix decrement is: 10
The value of c is: 10
clrscr();
int a = 10, b = 0, c = 0;
cout<< "The old value of a is: " << a << "\n";
// Prefix Increment
b = ++a; // Value is incremented first, then assigned
cout<< "The value of a after prefix increment is: " << a << "\n";
cout<< "The value of b is: " << b << "\n";
// Prefix Decrement
c = --a; // Value is decremented first, then assigned
cout<< "The value of a after prefix decrement is: " << a << "\n";
cout<< "The value of c is: " << c << "\n";
35
Operators in C++

