
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
When to use i++ or ++i in C++?
Increment operators are used to increase the value by one while decrement works opposite. Decrement operator decrease the value by one.
Pre-increment (++i) − Before assigning the value to a variable, the value is incremented by one.
Post-increment (i++) − After assigning the value to a variable, the value is incremented.
Here is the syntax of i++ and ++i in C++ language,
++variable_name; // Pre-increment variable_name++; // Post-increment
Here,
variable_name −Name of the variable given by user.
Here is an example of pre and post increment in C++ language,
Example
#include <iostream> using namespace std; int main() { int i = 5; cout << "The pre-incremented value: " << i; while(++i < 10 ) cout<<"\t"<<i; cout << "\nThe post-incremented value: " << i; while(i++ < 15 ) cout<<"\t"<<i; return 0; }
Output
The pre-incremented value: 56789 The post-incremented value: 101112131415
In the above program, the code of pre and post increment exists in main() function. The variable i of integer type is pre-incremented until value of i is less than 10 and post-incremented until the value of i is less than 15.
while(++i < 10 ) printf("%d\t",i); cout << "\nThe post-incremented vaue : " << i; while(i++ < 15 ) printf("%d\t",i);
- Related Articles
- When can I use a forward declaration in C/C++?
- When can I use a forward declaration C/C++?
- When Should I use Selenium Grid?
- When should I use an Inline script and when to use external JavaScript file?
- When should I use MySQL compressed protocol?
- When should I use a composite index in MySQL?
- What is a smart pointer and when should I use it in C++?
- Should I use , , or for SVG files?
- How do I use arrays in C++?
- Sum of the elements from index L to R in an array when arr[i] = i * (-1)^i in C++
- I want to use
- When should I use the keyword ‘this’ in a Java class?
- When should I use a semicolon after curly braces in JavaScript?
- How do I use the conditional operator in C/C++?
- When to use inline function and when not to use it in C/C++?

Advertisements