What is the >>>= operator in C?

CustomCalc picture CustomCalc · Aug 26, 2014 · Viewed 20.1k times · Source

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 literal? I have tested in Clang and GCC. There are no warnings and the output is "???"

#include <stdio.h>

int main()
{
    int a[2]={ 10, 1 };

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

    return 0;
}

Answer

Ilmari Karonen picture Ilmari Karonen · Aug 26, 2014

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.