Declaring 64-bit variables in C

后端 未结 5 1924
生来不讨喜
生来不讨喜 2020-12-01 17:41

I have a question.

uint64_t var = 1; // this is 000000...00001 right?

And in my code this works:

var ^ (1 << 43)
         


        
5条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-01 18:28

    As you supposed, 1 is a plain signed int (which probably on your platform is 32 bit wide in 2's complement arithmetic), and so is 43, so by any chance 1<<43 results in an overflow: in facts, if both arguments are of type int operator rules dictate that the result will be an int as well.

    Still, in C signed integer overflow is undefined behavior, so in line of principle anything could happen. In your case, probably the compiler emitted code to perform that shift in a 64 bit register, so by luck it appears to work; to get a guaranteed-correct result you should use the second form you wrote, or, in alternative, specify 1 as an unsigned long long literal using the ull suffix (unsigned long long is guaranteed to be at least 64 bit).

    var ^ ( 1ULL << 43 )
    

提交回复
热议问题