Codeforces and Polygon may be unavailable from December 6, 19:00 (UTC) to December 6, 21:00 (UTC) due to technical maintenance. ×

Behavior of the pre-increment (++p) and post-increment (p++) operators in cpp & Java

Revision en1, by ashwanikumarsharma, 2024-09-27 22:31:20

Anyone who know it properly, Please explain!

Cpp Code

#include<iostream>
using namespace std;

int main(){
    int p = 5;
    int q = ++p * ++p ;
    cout<<p<<endl;
    cout<<q<<endl;

    p = 5;
    q = ++p * p++;
    cout<<p<<endl;
    cout<<q<<endl;

    p = 5;
    q = p++ * ++p;
    cout<<p<<endl;
    cout<<q<<endl;

    p = 5;
    q = p++ * p++;
    cout<<p<<endl;
    cout<<q<<endl;

return 0;
}

Java Code

class incre{
    public static void main(String args[]){
        int p = 5;
        int q = ++p * ++p;
        
        System.out.println(p);
        System.out.println(q);

        p = 5;
        q = ++p * p++;

        System.out.println(p);
        System.out.println(q);

        p = 5;
        q = p++ * ++p;
        System.out.println(p);
        System.out.println(q);

        p = 5;
        q = p++ * p++;
        System.out.println(p);
        System.out.println(q);
    }
}

Cpp Output

7
49
7
42
7
35
7
30

Java Output

7
42
7
36
7
35
7
30

Although java output is obvious and it is what I expect but lots of confusion in Cpp

If possible attach some reliable document to read this

History

 
 
 
 
Revisions
 
 
  Rev. Lang. By When Δ Comment
en1 English ashwanikumarsharma 2024-09-27 22:31:20 1393 Initial revision (published)