How undefined are __builtin_ctz(0) or __builtin_clz(0)?

Unfortunately, even x86-64 implementations can differ – from Intel’s instruction set reference,BSF and BSR, with a source operand value of (0), leaves the destination undefined, and sets the ZF (zero flag). So the behaviour may not be consistent between micro-architectures or, say, AMD and Intel. (I believe AMD leaves the destination unmodified.) The newer LZCNT … Read more

What’s the best C++ way to multiply unsigned integers modularly safely?

Some template metaprogramming with SFINAE, perhaps. #include <type_traits> template <typename T, typename std::enable_if<std::is_unsigned<T>::value && (sizeof(T) <= sizeof(unsigned int)) , int>::type = 0> T safe_multiply(T a, T b) { return (unsigned int)a * (unsigned int)b; } template <typename T, typename std::enable_if<std::is_unsigned<T>::value && (sizeof(T) > sizeof(unsigned int)) , int>::type = 0> T safe_multiply(T a, T b) { … Read more

What specific hash algorithm does MessageDigest.getInstance(“SHA”) return?

The JCE Specification lists standard names that an implementation is expected to support. “SHA-1” is specified, as are SHA-256, SHA-384, and SHA-512. “SHA”, “SHA-0″ and SHA-2” are not standard names and therefore may not be supported at all. You cannot guarantee what “SHA” will return, if anything at all, because it is not in the … Read more

Can we change the value of an object defined with const through pointers?

It’s “undefined behavior,” meaning that based on the standard you can’t predict what will happen when you try this. It may do different things depending on the particular machine, compiler, and state of the program. In this case, what will most often happen is that the answer will be “yes.” A variable, const or not, … Read more

What’s a proper way of type-punning a float to an int and vice-versa?

Forget casts. Use memcpy. float xhalf = 0.5f*x; uint32_t i; assert(sizeof(x) == sizeof(i)); std::memcpy(&i, &x, sizeof(i)); i = 0x5f375a86 – (i>>1); std::memcpy(&x, &i, sizeof(i)); x = x*(1.5f – xhalf*x*x); return x; The original code tries to initialize the int32_t by first accessing the float object through an int32_t pointer, which is where the rules are … Read more

Is there a platform or situation where dereferencing (but not using) a null pointer to make a null reference will behave badly?

Classically, compilers treated “undefined behavior” as simply an excuse not to check for various types of errors and merely “let it happen anyway.” But contemporary compilers are starting to use undefined behavior to guide optimizations. Consider this code: int table[5]; bool does_table_contain(int v) { for (int i = 0; i <= 5; i++) { if … Read more