rizxt wrote:Gigasoft wrote:Hint: What type is 1 << bit?
Uhm, I'm pretty sure 1 is an integer by default... and bit is a unsigned char...
I don't get it...
I'm going to give you some C++ reference links. C is almost identical here.
cpp ref: operator arithmetic:
cppreference wrote:
Bitwise shift operators
...
The return type is the type of the left operand after integral promotions.
cpp ref: implicit conversion:
cppreference wrote:
Integral promotion
...
In particular, arithmetic operators do not accept types smaller than int as arguments, and integral promotions are automatically applied after lvalue-to-rvalue conversion, if applicable.
cpp ref: integer literal:
cppreference wrote:
Integer literal
...
The type of the literal
...
The type of the integer literal is the first type in which the value can fit, from the list of types which depends on which numeric base and which integer-suffix was used.
...
no suffix | decimal base
So, combining all of these together, 1 is int, the result of the shift of this 1 is int as well.
Now, how many bits are your ints (which, as we just determined, is the type of your "( 1 << bit )")? How many bits is uint64_t?
If you add the "ULL" suffix to your 1, that 1 will be an unsigned integer with at least 64 bits. It won't be truncated at/after position 31, which can give you undefined behavior:
cpp ref: operator arithmetic:
cppreference wrote:
Bitwise shift operators
...
For signed and non-negative a, if a * 2**b is representable in the unsigned version of the return type, then that value, converted to signed, is the value of a << b (this makes it legal to create INT_MIN as 1<<31); otherwise the behavior is undefined.
...
In any case, if the value of the right operand is negative or is greater or equal to the number of bits in the promoted left operand, the behavior is undefined.
C is slightly different here:
C2x N2478:
C2x wrote:
The result of E1 << E2 is E1 left-shifted E2 bit positions; vacated bits are filled with zeros. If E1 has
an unsigned type, the value of the result is E1 × 2**E2, reduced modulo one more than the maximum
value representable in the result type. If E1 has a signed type and nonnegative value, and E1 × 2**E2 is
representable in the result type, then that is the resulting value; otherwise, the behavior is undefined.
It's safer to be stricter as in C.
You need to learn the language better.