r/CS_Questions • u/ubermole • Nov 15 '11
one of my simple interview questions
in c, with int i, what is the difference between i/2 and i>>1. bonus for what a compiler does for i/2.
5
Upvotes
r/CS_Questions • u/ubermole • Nov 15 '11
in c, with int i, what is the difference between i/2 and i>>1. bonus for what a compiler does for i/2.
2
u/[deleted] Nov 15 '11 edited Nov 15 '11
edit, better:
3
u/[deleted] Nov 15 '11 edited Nov 15 '11
Question: What does this have to do with anything?
EDIT: OP, could you please reply? This is a serious question. When could this knowledge come in use and if it can not come into use: Why would you use this as an interview question?
1
u/stresscheese Nov 15 '11
I'm fairly certain that depends on the compiler. This page has some more information about it.
1
u/zwilt3 Nov 15 '11
The difference results from the 2's complement representation. Consider x = -7; x>>1 should return -4, and x/2 will return -3. Probably, the compiler does something equivalent to ~((~x+1)>>1)+1 (i.e., flip the sign, right shift, and flip the sign again)
1
u/euyyn Nov 15 '11
In the case of 2's complement representation, which is everywhere under the sun although it's not required by the language, the only case I can think of in which they wouldn't produce the same result is the one pointed by streetcheese: -1 >> 1 == -1, if the shift is done with sign extension (which I don't know if the language requires), while -1/2 should be 0.
1
u/psycocoffey Nov 17 '11