Archive for February, 2008

Memo to myself: code nuggets

This post is more for my own benefit than for the public out there. Whenever I do some coding (rarely, which is part of the problem) I come across a problem and, after some trying & researching, possibly a solution.

However, after some time this solution is lost in the depths of my source codes. And a new research is sometimes futile – plus I reject the notion of going through the hoops again, since I already should know what to do. So, now I’ll drop little code nuggets here, so I can find them again with less effort. It’s certainly not an entertaining post, but it helps me.

First item: toggling boolean variables

I like to work with boolean values, and sometime I need to toggle them. So a true becomes false and vice versa. Of course this should be a short oneliner. Not an if-else construct. A good approach is:

boolean = boolean ? false : true;

I tend to use the ?: operator ad nauseum… so  an even better approach is (and my preferred way to do it):

boolean ^= true;

What is this? A XOR assignment operator, similar to += or -= If boolean is true, then the XOR return false (because it is not an inclusive OR). If boolean is false, then the XOR returns true. Mission accomplished.

Creative Commons License - © 2007 Codecat - powered by WordPress