Thursday, August 02, 2007

l2program, noob!

Um, if you don't write C, C++, Java or a similar language, this post might be a bit obtuse.

So, the techniques I use when programming are constantly evolving. In this case, there's a feature of the (C++) language that I seldom if ever used before, but now use commonly when writing certain kinds of functions.

Specifically, I'm talking about the ability to write nested code blocks. People do this all the time with if and for statements:

if (condition) {
// A nested block
}

for(a;b;c) {
// Also a nested block
}

In this case, however, I'm talking about using that same construct completely on it's own, for two reasons:
  • It limits the scope of names

  • It also limits the scope of memory

If I need several temporary variables, but only for a few lines of code, and especially if they take a lot of memory, it becomes very attractive to declare them in a nested block:

{
double total;
{
vector temp = getSomeDataFromSomewhere();
for(int i=0; i<temp.size(); ++i) total += temp[i];
}
{
vector temp = getSomeOtherDataFromElsewhere();
for(int i=0; i<temp.size(); ++i) total += temp[i];
}
return total;
}

It's not a super-common use, though people do do it. That open-curly looks a little naked to me, since I'm not used to seeing it, but I've been finding it very handy lately, saving memory and making my code neater/cleaner.

Forgive the blatantly artificial example. In this case, naturally, I could have re-used the temporary vector (distasteful in it's own right, to be fair), and I also omitted the nested block for the contents of the loops, something I normally avoid even in cases as simple as this.

No comments: