• Home
  • 3.13 Increment and Decrement Operators

3.13 Increment and Decrement Operators

View Categories

3.13 Increment and Decrement Operators

1 min read

Table of Contents

The increment (++) and decrement (--) operators are unary operators used to increase or decrease the value of a variable by one. These operators are commonly used in loops, counters, and array indexing.

Both operators are available in two forms: prefix and postfix. The prefix form modifies the variable before its value is used, whereas the postfix form uses the current value first and then updates the variable.

Source Code #

#include <iostream>

int main()
{
    int value = 10;

    std::cout << "Initial Value : " << value << '\n';

    std::cout << "Prefix Increment  (++value): " << ++value << '\n';
    std::cout << "Postfix Increment (value++): " << value++ << '\n';
    std::cout << "Value After Postfix         : " << value << '\n';

    std::cout << "Prefix Decrement  (--value): " << --value << '\n';
    std::cout << "Postfix Decrement (value--): " << value-- << '\n';
    std::cout << "Value After Postfix         : " << value << '\n';

    return 0;
}

Output #

Initial Value : 10
Prefix Increment  (++value): 11
Postfix Increment (value++): 11
Value After Postfix         : 12
Prefix Decrement  (--value): 11
Postfix Decrement (value--): 11
Value After Postfix         : 10

Explanation #

  • The increment operator (++) increases the value of a variable by one.
  • The decrement operator (--) decreases the value of a variable by one.
  • The prefix increment operator (++value) increments the variable before its value is used in the expression.
  • The postfix increment operator (value++) uses the current value first and increments the variable afterward.
  • The prefix decrement operator (--value) decrements the variable before its value is used.
  • The postfix decrement operator (value--) uses the current value first and decrements the variable afterward.
  • Increment and decrement operators can only be applied to modifiable variables.
  • return 0; terminates the program successfully.

Powered by BetterDocs

Leave a Reply

Your email address will not be published. Required fields are marked *