N
N
Nikich2019-10-12 18:07:57
Java
Nikich, 2019-10-12 18:07:57

Why in java would i += i++ result in 0?

The source code looks like this:

for (x = 0, i = 0; x < 10; x++)
{ i += i++; 
System.out.print(i+"\t"); }

Why is it outputting 0 when compiling?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Armenian Radio, 2019-10-12
@Nikkich

i++ - postfix increment. Since there are no bells and whistles with a sequence point from C++ and C, it will definitely work here:
i+=i++ can be rewritten as
result=i+i++ without any problems
;
+0
i=1
we count the addition 0 + 0 (the value that was in i before the expression was evaluated, and what we pulled out during the prefix increment)
result=0
i=1
now we write the result of adding 0 to 0 into i, overwriting earlier 1 written there.
i=result //here i will be written 0

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question