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.
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.
#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;
}
#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;
}
class Operator {
public static void main(String[] args){
int var=5;
System.out.println(var++);
System.out.println("\n"+ ++var);
}
}
<?php
$var=5;
echo $var++."<br/>";
echo ++$var;
?>
The output of all these program is same.
Output
5 7
It takes a lot of effort and cost to maintain Programiz. We would be grateful if you support us by either:
Disabling AdBlock on Programiz. We do not use intrusive ads.
or
Donate on Paypal