Expert C Programming

(Jeff_L) #1

compound statement could be reused to process the braces-enclosed part of a switch. So a declaration
is naturally accepted, though it's futile to add an initial value as part of a declaration in a switch
statement, as it will not be exe-cuted—execution starts at the case that matches the expression.


Handy Heuristic


Need Some Temporary Store? Be the First on Your Block!


It is always the case in C that where you have some statements opening a block


{


statements


you can always add some declarations in between, like this:


{


declarations


statements


You might use this if allocating memory was expensive, and hence avoided if possible. A
compiler is free to ignore it, though, and allocate the space for all local blocks on calling a
function. Another use is to declare some variables whose use is really localized to this
block.


if ( a>b )


/ swap a, b /


{


int tmp = a;


a = b; b = tmp;


}


C++ takes this a step further still, and allows arbitrary intermingling of statements and
declarations, and even embedding declarations in the middle of "for" statements.


for (int i=0; i<100; i++){...


If not used with restraint, that can quickly lead to confusion.

Free download pdf