Thursday, July 14, 2011

FUNCTION

FUNCTION
A self-contained software routine that performs a task. Functions can do a large amount of processing or as little as adding two numbers and deriving a result. Values are passed to the function, and values may be returned. Or, the function may just perform the operation and not return a resulting value. The concept of a function within a program is that, once written, it can be used over and over again without the programmer having to duplicate the same lines of code in the program each time that same processing is desired.
Syntax:
return_type function_name(list of parameters);
Example:
int max(int n1, int n2);    /* A programmer-defined function */
int printf(const char *format,...);    /* From the standard library */
int fputs(const char *buff, File *fp);    /* From the standard library */

Local Variables

The scope of a variable is simply the part of the program where it may be accessed or written. If a variable is declared within a function, it is local to that function. Variables of the same name may be declared and used within other functions without any conflicts.
int fun1()
{
    int a;
    int b;
    ....
}

int fun2()
{
    int a;
    int c;
    ....
}
Here, the local variable "a" in fun1 is distinct from the local variable "a" in fun2. Changes made to "a" in one function have no effect on the "a" in the other function. Also, note that "b" exists and can be used only in fun1. "C" exists and can be used only in fun2. The scope of b is fun1. The scope of c is fun2. Note that main is also a function. Variables declared after the opening bracket of main will have all of main as their scope.

External Variables

Variables may also be defined outside of any function. These are referred to as global or external variables. The scope of an external variable is from its declaration to the end of the file.
int j;
...
int main()
{
    ....
}

int k;
float funA()
{
}
int l;
float funB()
{
}
The variable "j" will be visible in main, funA and funB. The variable "k" will be visible in funA and funB only. The variable "l" will be visible only in function funB.
An important distinction between automatic (local) variables and external (global) variables is how they are initialized. External variables are initialized to zero. Automatic variables are undefined. They will have whatever random value happens to be at their memory location. Automatic, or local, variables must always be initialized before use. It is a serious error, a bug, to use a local variable without initialization.

0 comments:

Post a Comment