Difference in Increment ++ Operator as Prefix and Postfix | ZenTek ZenTek: Difference in Increment ++ Operator as Prefix and Postfix
Contact Us:

If You Have Any Problem, Wanna Help, Wanna Write Guest Post, Find Any Error Or Want To Give Us Feedback, Just Feel Free To Contact Us. We Will Reply You Soon.

Name: *


Email: *

Message: *


ZenTek

LiveZilla Live Help

Difference in Increment ++ Operator as Prefix and Postfix

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
Like the Post? Share with your Friends:-

Team SB
Admin: Akash

0 comments:

POST A COMMENT

Contact Us

Name

Email *

Message *

 

About Me

Hello Guys

I am an IT(Information Technology) Student design this blog for your Preference I always enjoyed technical things as a kid

now here i am sharing my knowledge about Tips and Tricks In Internet PC Windows Free Recharges and Other Cool Stuffs Too

So enjoy it

Followers

Widget by : ZenTek
Widget by : ZenTek
Copyright © . ZenTek. All Rights Reserved.
Designed by :-Way2themes