{
public static void main(String[] args) {
int a = 10;
if (a == a--)
System.out.println("first\t");
a=10;
if(a==--a)
System.out.println("second\t");
}
}
For the java program, output is "first", whereas for the C/C++ program its "second". The functionality of post/pre fix operations are same in both programs to my knowledge. If anyone can shed some light on the logic, it would be great as I am new to coding.
int main()
{
int a = 10;
if(a==a--)
printf("first\t");
a=10;
if(a==--a)
printf("second\t");
}
In java, you get the guarantee that you'll always observing this code printing First, and never Second.
In C/C++, you get no such guarantees. Depending on compiler, architecture, OS, and phase of the moon, it will likely print either only First or Second but I'm pretty sure the C and C++ spec make it 'legal' for a compiler/architecture/OS/phase-of-moon combo to end up printing BOTH First and Second or even neither.
See order of evaluation rules for C++: Given some binary operator construct: a x b where a and b are expressions and x is some binary operator, then first a and b must be evaluated, and then the x operator is applied to the values so obtained. Unless the operator explicitly decrees an order (which for example the || and && operators do; they promise to short-circuit, that is, to not evaluate b at all, if a is such b cannot affect the result) - then a C(++) compiler is free to emit code such that b is evaluated before a is, or vice versa.
C is filled to the brim with such 'shoulds' and 'mays': The C spec is designed to allow C code to compile on a wide variety of chips with a ton of leeway for a compiler to apply far-reaching optimizations. It goes so far that simple primitive data types have an unspecified bitwidth.
Contrast to java, where almost everything is locked down: There are very few aspects of java code which are intentionally left unspecified, and the compiler is 'on rails' and is very very limited in what bytecode it is allowed to emit (in java, the optimizations are left to the runtime / hotspot compiler, not to javac).
That's why, on java, the spec DOES define explicitly precisely how a x b ought to be resolved: the java spec does decree that regardless of operator, a must always be evaluated before b is evaluated (unless, just like in C, b isn't evaluated at all due to short-circuit rules).
Going all the way back to the Java Language Specification v7, the spec explicitly dictates the left hand side MUST be evaluated first - and this hasn't changed since then (and I'm pretty sure was true since java 1.0, for what it's worth. It's probably chapter 15.7.1 in most JLS versions).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With