Home > Articles > Programming > C/C++

What Is C For?

  • Print
  • + Share This
From the author of

Sensible Scoping

One of the best things about C99 was that it allowed for easy implementation of the principle of "smallest scope": In good code, every variable should be valid for only as long as it’s needed. In C89, you could define variables only at the start of blocks. In C99, you can define them anywhere.

One really nice addition, taken from C++, was the ability to declare variables in for loop initializers that had the scope of the loop. Constructs like this are very useful:

for(unsigned int i=0 ; i<n ; i++)

The variable i is now valid for the duration of the loop. While this is nice, it introduces a very irritating inconsistency into the language. If you can declare variables in for loops, why not in other control structures? Being able to declare them in if statements, for example, would often be very clean. Imagine being able to write something like this:

if(int i = foo())

This would declare i and set it to the return value from foo(). This variable would be valid for the scope of the if statement. At the moment, to introduce this kind of scope, you have to do this:

int i = foo();

The scope of i then persists outside the if statement. You could prevent this problem by wrapping the whole thing in a block, but then the proliferation of braces starts to make your code look like a weird dialect of LISP.

Being able to declare scoped variables in all control structures, not just for loops, would go a long way toward avoiding scope leakage.

  • + Share This
  • 🔖 Save To Your Account