My brain can't comprehend this

What will be the output of the following program?

1
2
for(int i = 0; i < 5; i = i++)
    print(i); //print out the result


Note: This problem is language agnostic, meaning that it is language independent.

It will print 0 indefinitiely It will print numbers from 0 to 4 Syntax Error It will print numbers from 0 to 5

This section requires Javascript.
You are seeing this because something didn't load right. We suggest you, (a) try refreshing the page, (b) enabling javascript if it is disabled on your browser and, finally, (c) loading the non-javascript version of this page . We're sorry about the hassle.

1 solution

Arulx Z
May 15, 2015

This behaviour is well defined and i = i++ works in the following way:

  1. First it evaluates expression i++. Evaluation of this expression produces an expression value (which is the value of i before increment) and increments i.

  2. Later it assigns the expression value to i, overwriting incremented value.

So value of i never increases and thus 0 will be printed indefinitely.

0 pending reports

×

Problem Loading...

Note Loading...

Set Loading...