Friday, April 15, 2011

Compile-Time Tips and Tricks

Mike Ash:

With a bit of trickery, it’s possible to build a check which happens at compile time, late enough so that types are known, but before your program actually runs. There are actually a few different ways to do this, but my preferred way is to declare an array whose size depends on the expression to test. If it passes, set the size to 1, which compiles. If it fails, set the size to -1, which is illegal and causes an error. The error message cannot be fully customized, but by giving the array a descriptive name, the message can still be conveyed.

1 Comment RSS · Twitter


All those obscure tricks needed to make simple compile time checks is what pushes me away from the C-family languages and more towards the D programming language.

static assert((void*).sizeof == 8, "Not 64-bit!");

Still, it's a nice trick for when playing in the C family.

Leave a Comment