Saturday, May 16, 2009

My amazing coding discovery

I just discovered that in C and Java (and presumably other languages as well), the following is perfectly valid syntax:
var1 = var2 = var3 = something;
To, as is reasonably obvious, the value of the three variables to something. Which (to me) is a whole lot nicer than doing the same over three lines, as I've always been a big fan of not using extra lines unnecessarily. This goes up there with my other favourite space saving technique, the ternary operator which takes the form:
var = boolean ? someValue : someOtherValue;
Where if the boolean evaluates to being true, var will be set to someValue and if it is false, someOtherValue. You've done on one line what would've taken four with if/else statements! I've even been tempted to use nested ternary operators sometimes, but this quickly becomes illegible, which ain't the best.

Anyways, back to the = = = thing, I actually first found that out in a physics lab a couple of weeks back, when I had to set three registers to the same value on the microcontroller to set up three timers I think it was. Though I was having issues at that point so I think I just changed it back to make sure it'd work. I then had the perfect situation to use it on our group project, and it worked fine, so I'm never going to look back. I haven't learned such a trivial yet handy language feature like that in a while so it felt like when I had just learnt about var++ and var *= something and the like.

And, three quarters of the way through writing my first blog post I change from using the nice (but laggy - being google probably lots of javascript) rich text editor I've gone to using the plain html - go figure.

No comments:

Post a Comment