Question

I was just asked a question in a technical interview that I was a bit confused about.

The question was as follows:

If

int i = -1, int j = -1, and int k = -1, 

and we run the following line:

++i && ++j && ++k

what would be the new values of i, j, and k? The reason I was confused is that, since we are not assigning this expression to anything, it doesn't seem like the and operators should make any difference (only the increment operators should). However, running a simple test program quickly proved that I was mistaken. Could someone explain this to me, as I have never seen this exercise before.

Était-ce utile?

La solution

The key here is that && is short-circuiting.

So, ++i is evaluated first. It increments i and returns the new value, which is 0, so the rest of the expression doesn't get evaluated.

The values should be 0, -1, -1 if I'm not mistaken.

Autres conseils

The value of the expression ++i is 0 in this case, which is to say false so the and operation shortcuts and the latter expressions are never evaluated.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top