Why can int _$[:>=<%-!.0,}; compile?

Today I found strange syntax like

 int _$[:>=<%-!.0,};

in some old code, but in fact the code is not commented. There seems to be no report of compile errors for this line. I tested it separately and it can compile too:

int main(){
    int _$[:>=<%-!.0,};
    return 0;
}

Why can it compile?


Solution 1:

With Digraph (see below), the line is converted to:

int _$[]={-!.0,};

On the right hand side, .0 is the double literal, ! is the logical negation operator, - is the arithmetic negation operator, and , is the trailing comma. Together {-!.0,} is an array initializer.

The left hand side int _$[] defines an int array. However, there's one last problem, _$ is not a valid identifier in standard C. Some compilers (e.g, gcc) supports it as extension.


C11 §6.4.6 Punctuators

In all aspects of the language, the six tokens

<: :> <% %> %: %:%:

behave, respectively, the same as the six tokens

[  ]  {  }  #  ##

Solution 2:

Well,

  • underscore _ is an allowed identifier character,
  • dollar sign $ is allowed in some implementations too,
  • left bracket [ denotes the type should be array,
  • :> is the digraph for ],
  • equals = is assignment,
  • <% is the digraph for {,
  • -!.0 is just -1 (.0 is a double literal 0.0, ! implicitly casts to (int) 0 and logically inverts it, and - is negative),
  • you can have trailing commas in array initializers {1, (2, 3,)},
  • and ; ends the statement.,

So you get

int _$[] = {-1,};

Solution 3:

If we replace the digraphs :> and <% present in your line of code, we end up with

int _$[]={-!.0,};

which is equivalent to

int _$[] = { -1, };

It is a declaration of array _$ of type int [1] with an initializer.

Note that this is not exactly guaranteed to compile since standard C language does not immediately provide support for $ character in indentifiers. It allows implementations to extend the set of supported charaters though. Apparently the compiler you used supported $ in identifiers.