Turbo C++ (not visual)(Postfix and prefix operators)
-
20-06-2021 - |
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 :(
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.
- Evaluate
a--
first (returns10
), then--a
(returns8
), then substract (returns2
). - Evaluate
--a
first (returns9
), thena--
(returns9
), then substract (returns0
).
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.