Demonstration of Prefix and Postfix operators in C++

By: Emiley J Emailed: 1674 times Printed: 2153 times    

Latest comments
By: rohit kumar - how this program is work
By: Kirti - Hi..thx for the hadoop in
By: Spijker - I have altered the code a
By: ali mohammed - why we use the java in ne
By: ali mohammed - why we use the java in ne
By: mizhelle - when I exported the data
By: raul - no output as well, i'm ge
By: Rajesh - thanx very much...
By: Suindu De - Suppose we are executing

Both the increment operator (++) and the decrement operator(--) come in two varieties: prefix and postfix. The prefix variety is written before the variable name (++myAge); the postfix variety is written after (myAge++).

In a simple statement, it doesn't much matter which you use, but in a complex statement, when you are incrementing (or decrementing) a variable and then assigning the result to another variable, it matters very much. The prefix operator is evaluated before the assignment, the postfix is evaluated after.

The semantics of prefix is this: Increment the value and then fetch it. The semantics of postfix is different: Fetch the value and then increment the original.

This can be confusing at first, but if x is an integer whose value is 5 and you write

int a = ++x;

you have told the compiler to increment x (making it 6) and then fetch that value and assign it to a. Thus, a is now 6 and x is now 6.

If, after doing this, you write

int b = x++;

you have now told the compiler to fetch the value in x (6) and assign it to b, and then go back and increment x. Thus, b is now 6, but x is now 7. Listing below shows the use and implications of both types.

A demonstration of prefix and postfix operators.

1:  // Listing 4.3 - demonstrates use of
2:  // prefix and postfix increment and
3:  // decrement operators
4:  #include <iostream.h>
5:  int main()
6:  {
7:      int myAge = 39;      // initialize two integers
8:      int yourAge = 39;
9:      cout << "I am: " << myAge << " years old.\n";
10:     cout << "You are: " << yourAge << " years old\n";
11:     myAge++;         // postfix increment
12:     ++yourAge;       // prefix increment
13:     cout << "One year passes...\n";
14:     cout << "I am: " << myAge << " years old.\n";
15:     cout << "You are: " << yourAge << " years old\n";
16:     cout << "Another year passes\n";
17:     cout << "I am: " << myAge++ << " years old.\n";
18:     cout << "You are: " << ++yourAge << " years old\n";
19:     cout << "Let's print it again.\n";
20:     cout << "I am: " << myAge << " years old.\n";
21:     cout << "You are: " << yourAge << " years old\n";
22:       return 0;
23: }
Output: I am      39 years old
You are   39 years old
One year passes
I am      40 years old
You are   40 years old
Another year passes
I am      40 years old
You are   41 years old
Let's print it again
I am      41 years old
You are   41 years old

Analysis: On lines 7 and 8, two integer variables are declared, and each is initialized with the value 39. Their values are printed on lines 9 and 10.
On line 11, myAge is incremented using the postfix increment operator, and on line 12, yourAge is incremented using the prefix increment operator. The results are printed on lines 14 and 15, and they are identical (both 40).

On line 17, myAge is incremented as part of the printing statement, using the postfix increment operator. Because it is postfix, the increment happens after the print, and so the value 40 is printed again. In contrast, on line 18, yourAge is incremented using the prefix increment operator. Thus, it is incremented before being printed, and the value displays as 41.

Finally, on lines 20 and 21, the values are printed again. Because the increment statement has completed, the value in myAge is now 41, as is the value in yourAge.


C++ Home | All C++ Tutorials | Latest C++ Tutorials

Sponsored Links

If this tutorial doesn't answer your question, or you have a specific question, just ask an expert here. Post your question to get a direct answer.



Bookmark and Share

Comments(2)


1. View Comment

Thanks for the above description, but pls let me know the output of the following program and how it came.

#define mul(x) x * x

int main()
{
int i=3;
printf("%d \n", mul(++i));
printf("%d", i);
return(0);
}


View Tutorial          By: Amit Goyal at 2009-09-25 05:33:10
2. View Comment

what will be the output of 'X' in following code and how ?

x=(i++ + ++i + i++ + i++ + ++i);


View Tutorial          By: Amit Goyal at 2009-09-25 05:48:45

Your name (required):


Your email(required, will not be shown to the public):


Your sites URL (optional):


Your comments:



More Tutorials by Emiley J
Password must include both numeric and alphabetic characters - Magento
What is Hadoop?
Returning multiple values from a web service
Tomcat and httpd configured in port 8080 and 80
Java Webservices using Netbeans and Tomcat
Java WebService connected to Database
How to Deploy a Java Web Service
Call a webservice in Java
Java WebService - Create your first web service in Java
package javax.jws does not exist
Getting Started with Android
HTML5 Location - getCurrentPosition() in HTML5
HTML5 Canvas - Using Canvas in HTML5
HTML5 - Introduction
HTML5 Video - Handling video in HTML5

More Tutorials in C++
Two-Dimensional Array Manipulation in C++
Calculate average using Two-Dimensional Array in C++
Compute the square root of the sum of the squares of an array in C++
Matrix using nested for loops in C++
Sorting an array of Strings in C++
Calculating total based on the given quantity and price in C++
Compiling and Linking Multiple Source Files in C++
Enumerations in C++
Program to add two numbers in C++
Comments in C++
while loop in C++
for loop in C++
Programming errors a compiler will detect in C++
if in C++
Using the Built-in Arithmetic Types in C++

More Latest News
Most Viewed Articles (in C++ )
C++ Recursion function explained using Fibonacci series
Sorting an array of Strings in C++
Dot (.) vs Arrow (->) to access data members in C++
Constructors and Destructors in C++
Using cout.width() in C++
virtual inheritance example in C++
Public versus Private members in C++
Where to Put Class Declarations and Method Definitions in C++
Calculating total based on the given quantity and price in C++
Demonstration of Prefix and Postfix operators in C++
The Birth, history and need for C++
Looping with the keyword goto in C++
while Loops in C++
while (1) Loops in C++
Converting C++ Multiple-Inheritance Hierarchies to Java
Most Emailed Articles (in C++)
Looping with the keyword goto in C++
Default arguments in C++
Compiling and Linking Multiple Source Files in C++
Difference between Procedural, Structured, and Object-Oriented Programming
Tutorial on Classes and Members in C++
for Loops in C++
Using switch Statements in C++
Operator Precedence in C++
How to handle Exceptions in C++
strcpy() and strncpy() sample program in C++
assert() example program in C++
Using peek() and putback() with cin in C++
Function overloading in C++
File in C++ - Writing text to a file in C++
Pass by Reference vs Pass Value in C++ functions