[ACCEPTED]-In C++, what is the difference between 1 and 1i64?-bit-shift

Accepted answer
Score: 11

1 has type int according to C++ Standard. On 14 64-bit Microsoft compiler int has sizeof = 4 13 bytes, it means that int is 32-bit variable. 1i64 has 12 type __int64.

When you use shift operator the type 11 of the result is the same as the type of 10 the left operand. It means that shifting 9 1 you'll get 32-bit result. Microsoft compiler 8 assumes that it could be not what you are 7 expecting (on 64-bit platform) and gives 6 you warning message.

When you use 1i64 result 5 will be 64-bit on both platforms. j and 0 will 4 be implicitly casted to 64-bit. So the whole 3 expression will be calculated in 64-bit 2 variables and result will be bool.

So using 1i64 is 1 safe on both (32/64) platforms.

Score: 4

The i64 suffix is Microsoft-specific. To be 14 more portable (if you're worried about that), you 13 might use the INT64_C() macro from stdint.h:

#include <stdint.h>

// ...

if ((j & (INT64_C( 1) << k)) != 0) { ... }

Unfortunately, MS 12 doesn't have stdint.h as part of their C library 11 (most other compilers seem to have it), but 10 fortunately you can get one from several 9 sources:

Now you'll have a 64-bit constant 8 that'll work with a wide variety of compilers.

As 7 far as why you might want or need the 64-bit 6 value, it depends on the types of the various 5 parts of the expression. It would be helpful 4 to know the types of id, j, and k to be able 3 to answer whether you need the the 'u' suffix 2 on the constant or not, and what effect 1 it might have.

Score: 1

1i64 I believe should be a signed, 64-bit 13 integer. I can't proclaim any expertise 12 in Microsoft's implementation, but in GCC, the 11 solution for supporting 64-bit integers 10 on 32-bit CPUs was to make long longs double-words 9 using structs and various black magic macros. Therefore, i64 8 should be compatible.

As to the last bit of voodoo 7 -- the only point in specifying 1u it is 6 because it's possible that if k is large 5 enough, the result of the shift would meet 4 / exceed 32-bits of storage, in which case 3 the outcome will be different if the LH 2 operand is treated as a signed or an unsigned 1 integer.

Score: 0

Since that code is 'and'ing the 64-bit variable 12 j with the (32-bit) result of a bit-shift, the 11 result will be 'expanded' to 64 bit by the 10 compiler.

You probably want to be in control 9 of how the second operand to the 'and' is 8 calculated, so the compiler suggests you 7 use the full 64 bits by making the first 6 operand an __int64. This is safe in 32 bit, but 5 you should actually look at the type of 4 j to decide on the operator being 32 or 64 3 bit.

That's especially important in the 2 second bit, where the result is used as 1 an index.

More Related questions