Function


Modular Design
• A valuable strategy when writing complex programs is to
break down the program into several smaller modules. A
module ( or function at it is called in C) is a small selfcontained
section of an algorithm.
• In modular design, each major program step is implemented
as an independent program module or subprogram. These
modules are then combined to form a complete program.
• Modular design is much easier to develop
• Testing separate smaller modules is easier than it is to test the
entire program at once
• Most professional programmers agree that modular design is
the best strategy to use to write a complex program

Modularity in C
• The C programming language fully supports modular design
through the concept of functions.
• A C function is a self-contained and independent block of
statements.
• Every C program consists of one or more functions.
• Any C function can call any of the other functions in a
program including itself and be called by any other function.
• The function main() is somewhat special in that program
execution begins with the first statement in main().
• All C programs must have a function called main().

Why Functions?
– Manageable program development
Your programs become modularized and much more readable if
they are broken down into components.
– Reusability
Functions are reusable since a function can be reused in many
different contexts without repeating parts of the program text.
– Easy to make change
functions hide details of operation from parts of the program that
don't need to know about them, thus clarifying the whole, and
easing the pain of making changes.

The Structure of a C Function
• C function consists of two parts
– Function header
• A C function begins with a header statement. The function
header specifies the name of the function, the type of value that
the function returns, a list of parameters (or formal parameters),
and the data type of each parameter.
– Function Body
• The function body specifies the task that the function will carry
out.
The general syntax of function header and body
Type function_name(type1 parm1,type2 parm2,…,typeN parmN)
{
// Body of the function
}
function_name is the name given to the function,
type is the data type of the value returned by
the function, type1 is the data type of the
first formal parameter, parm1 is the identifier for
receiving the data

Structure of Function: An Example

int max (int a, int b, int c) function header
{
int max_value;
max_value = a;
if ( b > max_value)
max_value = b;
 function body
if ( c > max_value)
max_value = c;
return (max_value);
}

Types of functions
• User defined functions
• Functions that you have defined by yourself
• Library functions
– Somebody else has already defined for you

Function Calls
• Function call analogy:
• Boss asks worker to complete task
–Worker gets information, does task, returns result
– Information hiding: boss does not know details

How to Call Function?
• A function can be invoked in two different
ways
– If the function does not return a value then
function is invoked by simply using its name
followed by a list of arguments.
Syntax:
Function_name(arg1, arg2,…,argN)

Here Function_name is the name of the function and
arg1, arg2, … argN is the data value (or actual
parameter) that will be passed to the function.The
arguments in the function call need to correspond to
parameters in the function definition.

Function Call from the main program: An
Example

main()
{
int x,y,z;
x = 10;
y = 30;
z = 15;
max3(x, y, z); /* call function */
}
void max3 (int a, int b, int c)
{
int max;
max = a;
if (max < b)
max = b;
if (max < c)
max = c;
printf("\n The largest of %d %d %d is %d", a,b,c, max;

}

Function That Returns A Value
• Almost all functions return a value to the caller function.
• The only exception to this is a function of type void.
• The type of value returned by a function is specified in the function
header.
• A function can return a single value at a time.
For example, the function square defined here returns a value of type float.
The return statement provides the mechanism for returning a value to
the caller function. The syntax of the return statement is
return ( expression );
Where expression is any valid C expression.
float square(float x)
{

return (x * x);
}
The return statement provides the mechanism for returning a value to
the caller function. The syntax of the return statement is
return ( expression );
Where expression is any valid C expression.

Calling a Function That Return A Value
• The caller function should receive or use the value returned by the
calling function.
For an example:
main()
{
int x, y, z, largest;
largest = max3 ( x, y, z);

}
int max(int a, int b, int c)
{
int max;
...
}

Function Prototypes
• So that the C compiler can correctly interpret function calls it
is necessary to declare each C function before it is used in a
program.
• The C language provides a statement for declaring function
called a function prototype.
• A function prototype informs the compiler about the type of
value returned by the function and the type and number of
arguments that the function expects.
For example, the function prototype for the function max3() is
int max3 (int a, int b, int c);

The main Function
• In C, main is a special function that is called by the Operating System
when you execute your C program.
• It indicates the starting point of your program execution. Therefore, every
C program must contain a main function.
• It is the first function called in your program. Therefore if you have
multiple functions defined in your program, you must call them from
main function.
• The main function returns an integer that tells the operating system if the
program executed correctly.
• A return value of 0 normally means that everything went well, while a
non-zero value is normally an error code.
• The main function can also take arguments. They have the following
format:
int main(int argc, char **argv)
The value in argc is the number of command line parameters that you typed in
the console.

The Flow of Function Call
• Consider the following function definition and way they have
called.

void a(void)
{
printf(“A Starts\n”);
b();
c();
printf(“A Ends\n”);
}
void main()
{
a();
}

void b(void)
{
printf(“B Starts\n”);
c();
printf(“B Ends”\n”);
}
void c(void)
{
printf(“C Starts\n”);
printf(“C Ends\n”);
}

What do you think will be printed?

Call by Value
• Consider the following…
Guess the output of this program…
15 ?
void chang(int a)
{
a = a + 5;
}
void main(void)
{
int k = 10;
change(k);
printf(“%d\n”, k);
}
Wrong! Why?

Call by Value

• A C function is typically passed information from the calling function.
• The called function uses this information to perform its task and then
returns a result to the calling function.
• Although a function can use the values of the arguments provided by the
calling function, it cannot change the value of these arguments.
• This is because when a function is called the compiler evaluates each
argument and makes a copy of the argument.
• It is this copy that is passed to the function instead of the actual argument
itself.
• This mechanism of passing information to a function is known as call by
value.
• Since the function operates on copies of the arguments, the original
arguments in the calling function are not affected by anything that
happens within the function.

Local Variables

• Variable that are declared within the body of a function such as temporary
variables for storing intermediate results of calculations are local
variables.
• Local variables are visible only to the function in which they are defined
and are invisible to all other functions.
• Thus local variables can be accessed only from within the function. They
cannot be accessed by any other function.
• Local variables are also called automatic variables since they are
automatically created each time the function is called and are destroyed
after the function has completed execution.
• When a local variable is declared it initializes with an unknown or garbage
value. it is a good practice to initialize the local variables after declaration.

Example of Local Variable
#include <stdio.h>
void function1 (void);
main()
{
int i = 1; /* Local to main */

function1();
...
}
void function1(void)
{
int i = 10; /* Local to function1 */
...
}
Note that both i defined in main function and function1
are different and stores in different memory location.

Global Variables
• External or global variables, as they are
commonly called, are variables that are
defined outside a function.
• Global variables are visible to all functions
that follow the definition. The example that
follows creates two global variables seed and
new_seed.
• Unlike local variables, Global variables are
initialized to zero when they are declared.

Example of Global Variable
int random(void)
int reseed(void)
int seed; /* global variable */
main()
{
...
}
int new_seed; /* global variable */
int random(void)
{

}
int reseed( void)
{

}
The variable seed is visible to the function main(),
random(),and reseed(). The variable new_seed is visible to
random() and reseed() but not visible to main(), since it
was defined after main().

No comments

Powered by Blogger.