In any programming (Java, C Programming, PHP etc. ), increment ++ and decrement -- operator are used for increasing and decreasing the value of operand by 1 respectively.
Suppose, a=5 then,
++a; //a becomes 6
a++; //a becomes 7
--a; //a becomes 6
a--; //a becomes 5
Simple enough till now but, there is a slight but very important difference that a programmer should remember while using these operators.
++ and -- operator as prefix and postfix
If you use ++ operator as prefix like: ++var;
then, the value of operand is increased by 1 then, only it is returned but, if you use ++ as postfix like: var++;
then, the value of operand is returned first then, only it is increased by 1.
This is demonstrated by an example in these 4 different programming languages.
Languages |
---|
C Programming |
C++ Programming |
PHP |
Java |
C Programming Example
#include <stdio.h>
int main(){
int var=5;
printf("%d\n",var++);
/* 5 is displayed then, only var is increased to 6 */
printf("%d",++var);
/* Initially, var=6 then, it is increased to 7 then, only displayed */
return 0;
}
C++ Programming Example
#include <iostream>
using namespace std;
int main(){
int var=5;
cout<<var++<<"\n";
/* 5 is displayed then, only var is increased to 6 */
cout<<++var<<"\n";
/* Initially, var=6 then, it is increased to 7 then, only displayed */
return 0;
}
PHP Example
<?php
Svar=5;
echo $var++."<br/>";
echo ++$var;
?>
Java Example
class Operator {
public static void main(String[] args){
int var=5;
System.out.println(var++);
System.out.println("\n"+ ++var);
}
}
Output of all these program is same as below:
5
7
Post a Comment Blogger Facebook