简体   繁体   中英

Weird Java Syntax

I was doing a practice Computer Science UIL test form when I came across this problem:

What is output by the following?

int a = 5;
int b = 7;
int c = 10;
c = b+++-c--+--a;
System.out.println(a + " " + b + " " + c);

I put down the answer "No output due to syntax error" but I got it wrong. The real answer was 4 8 1! (I tested it out myself)

Can someone please explain to me how line 4 works?
Thanks

I added some parentheses:

int a = 5;
int b = 7;
int c = 10;
c = (b++) + (-(c--)) + (--a);
System.out.println(a + " " + b + " " + c);

b++ : b = b + 1 after b is used

c-- : c = c - 1 after c is used

--a : a = a - 1 before a is used

Look at it like this:

(b++) + (-(c--)) + (--a)

That should make more sense!

Look at Operator Precedence to see why it works this way.

Look at initialization of c like this, c = (b++) + (-(c--)) + (--a);

They had it compressed and intentionally confusing for your learning purposes. The code is essentially saying this, c = (b + 1) + (-(c - 1)) + (a - 1);

Break up the statement a bit. It's intentionally obfuscated.

c = b++ + -c-- + --a;

What this means:

  • The variable c is assigned the result of...
    • b (incrementation will take effect after this line), plus
    • the unary operation - of c (decrementation will take effect after this line), plus
    • a (decrementation takes immediate effect).

Replace the variables with the values, and you get:

c = 7 + (-10) + 4
c = 1

...and the result of your print statement should be:

4 8 0

Let's slow down, and look hard at the equation. Think about this carefully.

int a = 5;
int b = 7; 
int c = 10;
c = b+++-c--+--a;

b++ means increment b after assignment, so b stays equal to its original value in the equation, but will be incremented afterward the equation.

Then there's a +.

Then a negated c-- . c gets decremented but will remain the same for the equation.

Then add that to --a, which means a gets decremented immediately.

So the variables values at the print statement will be:

c = 7 + -10 + 4 = 1
a = 4
b = 8

May I add that in my opinion this is a bad question for a test. All its really asking is if you understand i++ vs ++i .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM