Thursday, July 24, 2008

DECLARATIONS AS STATEMENTS.

In a C++ program, a declaration can be placed wherever a statement can appear, which can be anywhere within a program block. Any initializations are done each time their declaration statement is executed. Suppose we are searching a linked list for a certain key:

int IsMember (const int key)
{
int found = 0;
if (NotEmpty())
{
List* ptr = head;
// Declaration

while (ptr && !found)
{
int item = ptr->data;
// Declaration

ptr = ptr->next;

if (item == key)
found = 1;
}
}
return found;
}

By putting declarations closer to where the variables are used, you write more legible code.

No comments: