Each time declaration statements for objects of storage class auto or register are executed, initialization takes place. The following example, from The continue Statement, shows initialization of the automatic object ch
inside the do
loop.
#include <conio.h>
// Get a character that is a member of the zero-terminated
// string, szLegalString. Return the index of the character
// entered.
int GetLegalChar( char *szLegalString )
{
char *pch;
do
{
// This declaration statement is executed once for each
// execution of the loop.
char ch = _getch();
if( (pch = strchr( szLegalString, ch )) == NULL )
continue;
// A character that was in the string szLegalString
// was entered. Return its index.
return (pch - szLegalString);
} while( 1 );
}
For each iteration of the loop (each time the declaration is encountered), the macro _getch
is evaluated and ch
is initialized with the results. When control is transferred outside the block using the return
statement, ch
is destroyed (in this case, the storage is deallocated).
See Storage Classes in Chapter 2 for another example of initialization.