Thursday, December 17, 2009

6.2 AUTOMATIC VARIABLES

Automatic variables are always declared within a function and are local to the function in which they are declared; that is,their scope is confined to that function.Automatic variables defined in different functions will therefore be independent of one another,even though they may have the same name.

Any variable declared within a function is interpreted as an automatic variable unless a different storage class specification is shown within within the declaration.This includes formal argument declarations.All of the variables in the programming examples encountered earlier have been automatic variables.

Since the location of the variable declarations within the program determines the automatic storage class, the keyword auto is not required at the beginning of each declaration.There is no harm in including an auto specifications within a declaration,though this is normally not done.

Consider once again the program mentioned in section 5.6 for calculating factorials.Within main, n is an automatic variable ,the formal argument n is also an automatic variable.

The storage class designation auto could have been included explicitly in the variable declarations if we had wished.Thus the program could have been written as follows.


/*calculate the factorial of an integer quantity using recursion*/


#include stdio.h


long int factorial (int n);     /*function prototype*/


main()
{
auto int n;
long int factorial (int n);


/*read in the integer quantity*/
printf ("n= ");
scanf ("%d", &n);

/*calculate and display the factorial*/

printf ("n!=%d\n", factorial(n));


}


long int factorial (auto int n)        /*calculate the factorial*/

{
if (n <= 1);
return(1);
else
return (n * factorial (n-1));

}

Either method is acceptable.As a rule, however, the auto designation is not included in variable or formal argument declarations,since this is the default storage class.Thus the program shown in 5.6 represents a more common programming style.

An automatic variable does not retain its value once control is transferred out of its defining function.There for any value assigned to an automatic variable within a function will be lost once the function is exited.

No comments:

Post a Comment