4 ms·
Found a disappointing bug in the test: (unsigned short)1 > -1 Correct answer is: implementation-defined. The left operand of > has type unsigned short, be
by kazinator 4y ago
Found a disappointing bug in the test:
(unsigned short)1 > -1
Correct answer is: implementation-defined.
The left operand of > has type unsigned short, before promotion. On C implementations for today's popular, mainstream machines, short is narrower than int; therefore, whether it is signed or unsigned it goes to int.
In that common case, we are doing a 1 > -1 comparison in the int type.
However, unsigned short may be exactly as wide as int, in which case it cannot promote to int, because its values do not fit into that type. It promotes to unsigned int in that case. Both sides will go to unsigned int{*}, and so we are comparing 1 > UINT_MAX which is 0.
Maybe the author should name this "GCC integer quiz for 32 bit x86", and drop the harder choices like "implementation-defined".
---
{*} It's more nuanced here. If we have a signed and unsigned integer operand of the same rank, it could go either way. If the unsigned type has a limited range so that all its vallues are representable in the signed type, then the unsigned type goes to signed. My remark represents only the predominant situation whereby signed and unsigned types of the same rank have overlapping ranges that don't fit into each other: the unsigned version of a type not only lacks negatives, but has extra positives.
- jwilk 4y agoDiscussed in this thread: https://news.ycombinator.com/item?id=32712578 https://news.ycombinator.com/item?id=32712578
- mort96 4y agoThe site says: > All other things being equal, assume GCC/LLVM x86/x64 implementation-defined behaviors.
- RicardoLuis0 4y agothat's still wrong, the integer data model is defined by the target, which is not specified in the quiz, not solely by the compiler, ex. clang uses 32-bit longs when compiling for windows, and 64-bit longs when compiling for linux: * windows - https://godbolt.org/z/WWWzarEsK https://godbolt.org/z/WWWzarEsK * linux - https://godbolt.org/z/57WK45o6e https://godbolt.org/z/57WK45o6e same for gcc on linux/windows (mingw)