Hello everybody
I was just surfing the net for interview questions and i get one expression in C++
It says so
long value;
//some stuff
value &= 0xFFFF;
and then
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++.
I am not able to find that what is the bug in this code .It ran perfectly well on my pc . Help would be appreciated .
Ok, well maybe I didn't word it properly but what I meant to say was....
You can't guarantee what the result will be, because the value of an unintialized variable is undefined so performing an AND operation on it will give an undefined result.
The sizes of long and int are implementation-dependent, not platform-dependent. Old versions (I don't know how old and I don't know if they stopped doing it) of Borland had 16-bit ints and 32-bit longs.
EDIT: There's nothing wrong with that code. The AND operation is perfectly valid and equivalent to value%=65536. Wanting to leave only the lower 16 bits of a value is useful is many circumstances.
GCC 4.4.1 says sizeof(int) is 4 and sizeof(long) is 8. I never knew that it was implementation dependant though, but it just makes sense.
I'm just thinking out loud(?) here, but I thought the purpose of a long was to have larger memory for an integer type. How exactly would you accomplish that with int and long having the same size?
Ultimately, I agree with Helios though. There really isn't anything wrong with the code, it compiles, and it doesn't crash at run-time so it really depends what you are trying to do with it though that would make it "logically" incorrect.
I thought the purpose of a long was to have larger memory for an integer type. How exactly would you accomplish that with int and long having the same size?
Well, that's more or less why we have different types, but in reality, a type is only guaranteed to be at least as big as the previous type in this order: char, bool, short, int, long. It's perfectly possible to make a compliant implementation where long is as big as char. This is (I'm guessing) because not every platform has as much variety of types as x86.
Thanks, I never did think of it that way. Perhaps I should study the ANSI standards a bit so that I know more about the details rather than just "what works on my computer".
If your platform uses 16Bit int, the the literal (0xFFFF) will be sign extended when usual arithmetic conversion takes place for the bitwise AND operation.
The code should be
1 2 3
long value(0);
//some stuff
value &= 0xFFFFL; //might even be 0x0FFFFL
Sign extension had crossed my mind (as I thought the original question was a trick question) - I thought
that 0xFFFF would be extended to 0xFFFFFFFF and there would be no change to the value - but when I tried it on mingw an MSVC it didn't happen like that.