Difference between the 2 expressions?

2
int p=4,u=12;

System.out.println(p=u);
System.out.println(p=+u);

I do not understand, what is the difference between the two expressions?

    
asked by anonymous 16.01.2018 / 15:45

2 answers

2

In theory it's quite different. One makes an assignment of a value contained in one variable to another variable. The other operates the value of a variable stating that it wants to apply a positive on it.

In practice it is the same thing. Because when you use the most unary operator (which is different from the binary where you make a sum), it is innocuous.

Remember math class? Positive with positive gives positive, positive with negative gives negative, that is, in this case it will always give the very value that it is being applied.

It's true (I doubt that some compiler works differently) that the language will make + a null operation and in execution there is no statement that does something because of the unary operator, then the performance will be the same. >

Some say that languages should not even have this operator since it does not do something useful. Some say that it can give a better semantics to the intended, even if it does not change the result.

The unary operator of negative already influences, since if the value is negative it becomes positive, according to the same math class.

It is often not recommended to use something that has a side effect such as expression . And this code does this. It calculates and assigns a value and already uses it as an argument of the method that will make the impression. This code would be best written as:

int p = 4, u = 12;
p = u;
System.out.println(p);
p = +u;
System.out.println(p);

But it depends on the context. In this nor would it need. In some I see no problem in using attribution as an expression.

I will not even get into the hypothesis of the question having a syntax error and the intention was to do something else.

    
16.01.2018 / 16:21
4

On first impression there is only one assignment the p receives the value of u

int p=4,u=12;
System.out.println(p=u);
Resultado: 12

In the second impression there is an assignment, however you use the unary operator + on the operand u :

int p=4,u=12;
System.out.println(p=+u); //é o mesmo que p = +(u) OU p = 1(u)
Resultado: 12

With the values above it is difficult to notice the difference, but in the example below note the change:

int p=4,u=-12;
System.out.println(p=-u); //é o mesmo que p = -(u) OU p = -1(u)
Resultado: 12

Here is a brief explanation of unary operator:

a = -b;

In the above example b is the operand that the - operator acts on.

    
16.01.2018 / 16:09