Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why does the same code work differently in java?

Tags:

java

c

I wrote following codes in java and C. But output of those programs are different. Java application gave 21 and C application gave 22 (I use GCC compiler).

Can you describe this ?

Here is the JAVA code.

class test
{

    public static void main(String args[])
    {
        int a =5;
        int b = (++a) + (++a) + (++a);
        System.out.println(b);
    }

}

Here is the C code.

#include <stdio.h>

int main( int argc, const char* argv[] )
{
int a =5;
int b = (++a) + (++a) + (++a);
printf("%d \n",b);
}
like image 745
Janaka Avatar asked Mar 09 '11 10:03

Janaka


2 Answers

int b = (++a) + (++a) + (++a);

This is undefined behavior in C, which means it can output 21, 22, 42, it can crash or do whatever else it wants to. This is UB because the value of a scalar object is changed more than once within the same expression without intervening sequence points

The behavior is defined in Java because it has more sequence points. Here's an explanatory link

like image 143
Armen Tsirunyan Avatar answered Oct 01 '22 19:10

Armen Tsirunyan


In Java evaluation is left to right, so the result is consistent. 6 + 7 + 8 == 21

like image 23
Costis Aivalis Avatar answered Oct 01 '22 20:10

Costis Aivalis