This was an interview question. I said they were the same, but this was adjudged an incorrect response. From the assembler point of view, is there any imaginable difference? I have compiled two short C programs using default gcc optimization and -S to see the assembler output, and they are the same.
--i decrements i by 1 then gives you the value of i (4). i-- gives you the value of i (5) then decrements it by 1. Both will give you the same result in a for loop.
i = i+1 will increment the value of i, and then return the incremented value. i++ will increment the value of i, but return the original value that i held before being incremented.
While the expression i-1 always execute the operation before to use the result (it behaves as a prefixed decrement operator), using increment or decrement operators as prefix the action, increment or decrement, is performed first then the result is used.
The difference is that one modifies the data-structure itself (in-place operation) b += 1 while the other just reassigns the variable a = a + 1 .
The interviewer may have wanted an answer something like this:
i=i+1
will have to load the value ofi
, add one to it, and then store the result back toi
. In contrast,++i
may simply increment the value using a single assembly instruction, so in theory it could be more efficient. However, most compilers will optimize away the difference, and the generated code will be exactly the same.
FWIW, the fact that you know how to look at assembly makes you a better programmer than 90% of the people I've had to interview over the years. Take solace in the fact that you won't have to work with the clueless loser who interviewed you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With