Probably the single most impactful epiphony I’ve had in my years of programming in C/C++ is discovering the ability to provide explicit scope inside a function. For snippets of code that are conceptually self-contained, but only used once in the program, they improve readability, provide optimization hints to the compiler, and are just kind of cool =)
Here’s some “before” code, like you’d expect to see throughout C source code:
int func1(int param1, int param2)
{
int ret = GREAT_SUCCESS;
int tmp1, tmp2;
structType struct1;
otherStructType struct2;
struct1.val1 = param1;
struct1.val2 = 20;
/*! do something */
ret = func2(&struct1);
if(FAILED(ret)) { return ret; }
struct2.whatever = param2;
struct2.somethingElse = 4;
/*! do something else */
ret = func2(&struct2);
if(FAILED(ret)) { return ret; }
return ret;
}
The variables are declared at the top of the function, the parameters for each function call
are determined, the struct parameter is filled out, return code checked.
Compare to using explicit scope:
int func1(int param1, int param2)
{
int ret = GREAT_SUCCESS;
/*! do something */
{
structType struct1;
struct1.val1 = param1;
struct1.val2 = 20;
ret = func2(&struct1);
if(FAILED(ret)) { return ret; }
}
/*! do something else */
{
otherStructType struct2;
struct2.whatever = param2;
struct2.somethingElse = 4;
ret = func2(&struct2);
if(FAILED(ret)) { return ret; }
}
return ret;
}
What this has accomplished is your eyes immediately see that “do something” and “do something” else
are functional blocks, which you can quickly read as independent units. In addition, you can very
easily tell that the function simply “does something”, then “does something else”, then returns the result.
Each functional block has it’s variables declared only inside it’s explicit scope. So you don’t have this huge block of declarations at the top of your function, making things much easier to read. Also, the compiler now knows without ambiguity which variables are used where, which can help optimize it’s memory usage (e.g. it can re-use stack space instead of reserving it all at the top).
To me, the difference is night and day – and this is only a really simple example. Try it out on some
more complex code, and watch your code quality/readability improve. This works in both C and C++, it’s
particularly great for C since you normally are forced to declare your variables at the top of the function.
When you explicitly declare your scope, this is no longer the case! Really, C just makes you declare at the
start of {} blocks.