Tuesday, 3 January 2012

Truth

A quick call out to the truthiness operator in C++, Ruby and Javascript (and probably other languages):

bool b = !!obj;

This will convert an object into its logically true or false value. For example, it will convert a pointer to true if it is non-null, or false if it is null. And it will convert a numerical object to true if it is non-zero, or false if it is zero. And similarly for nil/undefined in the aforementioned languages.

Of course, as anyone who knows about tokenisation in these languages will tell you, it's really just the ! operator applied twice. And the ! operator is really the 'falsiness' operator.

But it's a useful construct to learn, and it's the most succinct way of expressing what it does.

No comments:

Post a Comment