Increment ++ and Decrement -- Operator as Prefix and Postfix

In programming (Java, C, C++, PHP etc. ), increment ++ operator increases the value of a variable by 1 and decrement -- operator decreases the value of a variable by 1.

Suppose, a = 5 then,
++a;          //a becomes 6
a++;          //a becomes 7
--a;          //a becomes 6
a--;          //a becomes 5

Simple enough till now. However, there is a slight but important difference you should know when these two operators are used as prefix and postfix.

++ and -- operator as prefix and postfix

Suppose you use ++ operator as prefix like: ++var. The value of var is incremented by 1 then, it returns the value.

Suppose you use ++ operator as postfix like: var++. The original value of var is returned first then, var is incremented by 1.

This is demonstrated examples in 4 different programming languages.

Example #1: C Programming

#include <stdio.h>
int main()
{
  int var=5;
  
  // 5 is displayed then, var is increased to 6.
  printf("%d\n",var++);  
  
  // Initially, var = 6. It is increased to 7 then, it is displayed.  
  printf("%d",++var);    
 
  return 0; 
}

Example #2: C++

#include <iostream>
using namespace std;

int main()
{
   int var=5;

   // 5 is displayed then, var is increased to 6.
   cout << var++ << endl;

   // Initially, var = 6. It is increased to 7 then, it is displayed.
   cout << ++var << endl;

   return 0; 
}

Example #3: Java Programming

class Operator {
    public static void main(String[] args){
          int var=5;    
          System.out.println(var++);          
          System.out.println("\n"+ ++var);    
         }
    }

Example #4: PHP

<?php 
   $var=5;                   
   echo $var++."<br/>";    
   echo ++$var;             
?>

The output of all these program is same.

Output

5
7