Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Arithmetic C++ Operators

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.

like image 608
John Roberts Avatar asked Oct 19 '12 19:10

John Roberts


2 Answers

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.

like image 187
Luchian Grigore Avatar answered Nov 08 '22 00:11

Luchian Grigore


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.

like image 31
dmckee --- ex-moderator kitten Avatar answered Nov 08 '22 01:11

dmckee --- ex-moderator kitten