-3

I have a function:

(C++)

int a,b;

int getItself(int itself,int dummy)
{
    return itself;
}

int a=10;
int b=20;
a=getItself(b,b=a);

(java)

public static int getItself(int itself, int dummy)
{
    return itself;
}

public static void main(String[] args)
{
    int a = 10;
    int b = 20;

    a = getItself(b, b = a);
}

And the result is surprising: C++ can not do the swap while java can! I don't quite get why it occurs in that way. I thought both would first copy b to "itself", set a to b, and copy b to "dummy".

I would credit this code to this post: How to write a basic swap function in Java

W.Joe
  • 335
  • 2
  • 8

1 Answers1

1

This is because of order of evaluation. In java it is fixed from left to right where as in c++ its undefined and is a compile time choice.

Your getItSelf function depends on whether b is passed first or b=a is evaluated first. In java b will be passed first.

See c++ order of eval

Also see java order of eval

HariUserX
  • 1,341
  • 1
  • 9
  • 17