Loading collection data...
Collections are a way for you to organize kata so that you can create your own training routines. Every collection you create is public and automatically sharable with other warriors. After you have added a few kata to a collection you and others can train on the kata contained within the collection.
Get started now by creating a new collection.
When your C/C++ program behaves differently when you add/remove printing statements, it almost certainly means that it contains undefined behavior. I put your code in a static analyzer and it turns out that it contains undefined behavior when called with negative numbers.
Here is the culprit line:
In C/C++, the bitshift operators
<<
and>>
are only well defined when0 <= shift < width of the type being shifted
, with the width defined assizeof(type) * 8
, i.e. the number of bits in the type. Using these operators with a shift outside of this range is undefined behavior, and this happens in your code for negative numbers, the shift will be around260
.(Also,
*(unsigned int *)&f
violates the rules of a well-behaved C/C++ program. If you want to reinterpret the bits of a type into another type, you are supposed to usestd::memcpy()
/std::bit_cast()
since C++20).This comment is hidden because it contains spoiler information about the solution