Question

When I run this program I get output as 2

#include<iostream.h>
#include<conio.h>
void main(){
    clrscr();
    int a = 10;
    int c = a-- - --a;
    cout<<c;
    getch();
}

... but when I just modify it to

#include<iostream.h>
#include<conio.h>
void main(){
    clrscr();
    int a = 10,c;
    c = a-- - --a;
    cout<<c;
    getch();
}

... I get output 0. WHY? In java both the of them gave output as 2. Whats wrong with C++? Explain :(

Was it helpful?

Solution

Nothing wrong with C++, but there's something wrong in how you're using it.

The expression a-- - --a has undefined behavior in C++, and anything can happen.

The cleanest solution is to not write code like that (I wouldn't do it even if it were legal).

OTHER TIPS

To elaborate a bit on Luchian's answer. In C++, the order in which sub-expressions are evaluated inside an expression is not specified. This means that in the following expression:

int c = a-- - --a;

there are two equally valid evaluation orders.

  1. Evaluate a-- first (returns 10), then --a (returns 8), then substract (returns 2).
  2. Evaluate --a first (returns 9), then a-- (returns 9), then substract (returns 0).

This is meant to improve optimisation oportunities for compilers. Naturally, this means that in C++ it is a mistake to use expressions that depend on evaluation order, because there is no way to know which order the compiler will select. The trade-off between efficiency and error avoidance is different in C++ and in Java.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top