What is the >>>= operator in C?

后端 未结 3 658
滥情空心
滥情空心 2021-01-29 17:03

Given by a colleague as a puzzle, I cannot figure out how this C program actually compiles and runs. What is this >>>= operator and the strange 1P1

3条回答
  •  迷失自我
    2021-01-29 17:38

    The line:

    while( a[ 0xFULL?'\0':-1:>>>=a<:!!0X.1P1 ] )
    

    contains the digraphs :> and <:, which translate to ] and [ respectively, so it's equivalent to:

    while( a[ 0xFULL?'\0':-1 ] >>= a[ !!0X.1P1 ] )
    

    The literal 0xFULL is the same as 0xF (which is hex for 15); the ULL just specifies that it's an unsigned long long literal. In any case, as a boolean it's true, so 0xFULL ? '\0' : -1 evaluates to '\0', which is a character literal whose numerical value is simply 0.

    Meanwhile, 0X.1P1 is a hexadecimal floating point literal equal to 2/16 = 0.125. In any case, being non-zero, it's also true as a boolean, so negating it twice with !! again produces 1. Thus, the whole thing simplifies down to:

    while( a[0] >>= a[1] )
    

    The operator >>= is a compound assignment that bit-shifts its left operand right by the number of bits given by the right operand, and returns the result. In this case, the right operand a[1] always has the value 1, so it's equivalent to:

    while( a[0] >>= 1 )
    

    or, equivalently:

    while( a[0] /= 2 )
    

    The initial value of a[0] is 10. After shifting right once, it become 5, then (rounding down) 2, then 1 and finally 0, at which point the loop ends. Thus, the loop body gets executed three times.

提交回复
热议问题