Pre & post increment operator behavior in C, C++, Java, and C#

C++Server Side ProgrammingProgramming

The Pre increment and post increment both operators are used as increment operations. The pre increment operator is used to increment the value of some variable before using it in an expression. In the pre increment the value is incremented at first, then used inside the expression.

if the expression is a = ++b; and b is holding 5 at first, then a will hold 6. Because increase b by 1, then set the value of a with it.

Example Code

#include <iostream>
using namespace std;
main () {
   int a, b = 15;
   a = ++b;
   cout << a;
}

Output

16

Example Code

#include <stdio.h>
main () {
   int a, b = 15;
   a = ++b;
   printf(“%d”, a);
}

Output

16

Example Code

public class IncDec {
   public static void main(String[] args) {
      int a, b = 15;
      a = ++b;
      System.out.println(“” + a);
   }
}

Output

16

Example Code

using System;
namespace IncDec {
   class Inc {
      static void Main() {
         int a, b = 15;
          a = ++b;
          Console.WriteLine(""+a);
       }
   }
}

Output

16

The post increment operator is used to increment the value of some variable after using it in an expression. In the post increment the value is used inside the expression, then incremented by one.

if the expression is a = b++; and b is holding 5 at first, then a will also hold 5. Because increase b by 1 after assigning it into a.

Example Code

#include <iostream>
using namespace std;
main () {
   int a, b = 15;
   a = b++;
   cout << a;
   cout << b;
}

Output

15
16

Example Code

#include <stdio.h>
main () {
   int a, b = 15;
   a = ++b;
   printf(“%d”, a);
   printf(“%d”, b);
}

Output

15
16

Example Code

public class IncDec {
   public static void main(String[] args) {
      int a, b = 15;
      a = ++b;
      System.out.println(“” + a);
      System.out.println(“” + b);
   }
}

Output

15
16

Example Code

using System;
namespace IncDec {
   class Inc {
      static void Main() {
         int a, b = 15;
         a = ++b;
         Console.WriteLine(""+a);
         Console.WriteLine(""+b);
     }
   }
}

Output

15
16
raja
Published on 14-Mar-2019 11:06:41
Advertisements