I was having a look over this page: http://www.devbistro.com/tech-interview-questions/Cplusplus.jsp, and didn’t understand this question:
What’s potentially wrong with the following code?
long value; //some stuff value &= 0xFFFF;Note: Hint to the candidate about the base platform they’re developing for. If the person still doesn’t find anything wrong with the code, they are not experienced with C++.
Can someone elaborate on it?
Thanks!
Several answers here state that if an
inthas a width of 16 bits,0xFFFFis negative. This is not true.0xFFFFis never negative.A hexadecimal literal is represented by the first of the following types that is large enough to contain it:
int,unsigned int,long, andunsigned long.If
inthas a width of 16 bits, then0xFFFFis larger than the maximum value representable by anint. Thus,0xFFFFis of typeunsigned int, which is guaranteed to be large enough to represent0xFFFF.When the usual arithmetic conversions are performed for evaluation of the
&, theunsigned intis converted to along. The conversion of a 16-bitunsigned inttolongis well-defined because every value representable by a 16-bitunsigned intis also representable by a 32-bitlong.There’s no sign extension needed because the initial type is not signed, and the result of using
0xFFFFis the same as the result of using0xFFFFL.Alternatively, if
intis wider than 16 bits, then0xFFFFis of typeint. It is a signed, but positive, number. In this case both operands are signed, andlonghas the greater conversion rank, so theintis again promoted tolongby the usual arithmetic conversions.As others have said, you should avoid performing bitwise operations on signed operands because the numeric result is dependent upon how signedness is represented.
Aside from that, there’s nothing particularly wrong with this code. I would argue that it’s a style concern that
valueis not initialized when it is declared, but that’s probably a nit-pick level comment and depends upon the contents of the//some stuffsection that was omitted.It’s probably also preferable to use a fixed-width integer type (like
uint32_t) instead oflongfor greater portability, but really that too depends on the code you are writing and what your basic assumptions are.