Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C Programming: difference between ++i and i=i+1 from an assembler point of view?

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.

like image 962
Fandango Avatar asked May 15 '09 09:05

Fandango


People also ask

What is the difference between -- I and I --?

--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.

What is difference between i ++ and i 1?

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.

What is i 1 in C programming?

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.

What is the difference between i i 1 and i += 1?

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 .


1 Answers

The interviewer may have wanted an answer something like this:

i=i+1 will have to load the value of i, add one to it, and then store the result back to i. 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.

like image 177
Kristopher Johnson Avatar answered Sep 18 '22 17:09

Kristopher Johnson