Sei sulla pagina 1di 24

C

Functions in C

CSC 1102 - Programming Language 1 (C)


2005-2006 AIUB PL1 Development Team

Modular Design

A valuable strategy when writing complex


programs is to break down the program into
several smaller modules. A module ( or func
tion at it is called in C) is a small self-contain
ed section of an algorithm.
In modular design, each major program step
is implemented as an independent program
module or subprogram. These modules are t
hen 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 conc
ept 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

Reusability

Your programs become modularized and


much more readable if they are broken down
into components.

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, t
he type of value that the function returns, a list of p
arameters (or formal parameters), and the data typ
e of each parameter.

Function Body

The function body specifies the task that the


function will carry out.
Type function_name(type1
parm1,type2
parm2,,typeN
parmN)
The general syntax
of function
header and
body

{
// 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;
if ( c > max_value)
max_value = c;
return (max_value);
}

function body

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
main

worker1

worker4

worker2

worker5

worker3

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 follow
ed 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 p
arameters 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.

float square(float x)
{
return (x * x);
}

The return statement provides the mechanism for


returning a value to the caller function. The syntax o
f the return statement is
return ( expression );
Where expression is any valid C expression.

Calling a Function That Returns


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);

Main (Caller)
Function

}
int max(int a, int b, int c)

Calling Function

{
int max;
...
}

Function Prototypes
So that the C compiler can correctly
interpret function calls it is necessary to dec
lare each C function before it is used in a pr
ogram.
The C language provides a statement for
declaring function called a function prototyp
e.
A function prototype informs the compiler
about the type of value returned by the
function and the type and number of argum
ents 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
c();
printf(B
}
void c(void)
{
printf(C
printf(C
}

What do you think will be printed?

Starts\n);
Ends\n);

Starts\n);
Ends\n);

The Flow of Function Call

The way a function calls the


opposite it returns back
void main()
{
a();
}

Call by Value

Consider the following


void change(int a)
{
a = a + 5;
}
void main(void)
{
int k = 10;
change(k);
printf(%d\n, k);
}

Guess the output of this program


15 ? 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 functi
on.
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 func
tion 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 inter
mediate 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 f
unctions.
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 fu
nction 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;
main()
{
...
}
int new_seed;
int random(void)
{

}
int reseed( void)
{

/* global

variable */

/* global

variable */

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(), sinc
e it was defined after main().

Recursion

Example
int rec(int x);
void main(){
int a, fact; printf(Enter a number);
scanf(%d,&a);
printf(Factorial Value %d,rec(a));
int rec(int x){
if(x==1) return (1);
else
int f=x*rec(x-1);
return f;
}

Recursion, Lets Say, x=3


int rec(int x){
int f;
if(x==1) return (1);
else
f=x*rec(x-1);
return f;
}

int rec(int x){


if(x==1)
return (1);
else
int f=x*rec(x-1);
return f;
}

void main(){
int a; printf(Enter a number);
scanf(%d,&a);
printf(Factorial Value %d,rec(a));

int rec(int x){


if(x==1)
return (1);
else
int f=x*rec(x-1);
return f;
}

Potrebbero piacerti anche