Why does the same code work differently in Java?

I wrote the following code in Java and C, but the output of these programs is different

Can you describe it

This is java code

class test
{

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

}

This 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);
}

Solution

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

This is undefined behavior in C, which means it can output 21, 22, 42, it can crash or do anything else you want This is UB because the value of a scalar object changes more than once in the same expression without interfering with sequence points

This behavior is defined by Java because it has more sequence points Here’s an explanatory link

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>