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

Правка en1, от 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

История

 
 
 
 
Правки
 
 
  Rev. Язык Кто Когда Δ Комментарий
en1 Английский ashwanikumarsharma 2024-09-27 22:31:20 1393 Initial revision (published)