Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
2 views18 pages

Kome Text

The document discusses the concept of functions in C programming, detailing their declaration, definition, and usage. It emphasizes the importance of breaking programs into manageable functions for easier coding, testing, and maintenance. Additionally, it covers function calls, parameter passing, and the scope of variables, highlighting how functions enhance program organization and facilitate collaborative development.

Uploaded by

banishalyngwa99
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views18 pages

Kome Text

The document discusses the concept of functions in C programming, detailing their declaration, definition, and usage. It emphasizes the importance of breaking programs into manageable functions for easier coding, testing, and maintenance. Additionally, it covers function calls, parameter passing, and the scope of variables, highlighting how functions enhance program organization and facilitate collaborative development.

Uploaded by

banishalyngwa99
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

Functions

e Using functions
e Function declaration
e Function definition

¢ Function call

© Scope of variables

® Call-by-value and call-by-reference

© Storage classes
© Recursive functions
© Tower of Hanoi

4.1 INTRODUCTION

C enables programmers to break up a program into


segments commonly known as functions, each of which
can be written more or less independently of the others.
Every function in the program is supposed to perform a
well-defined task. Therefore, the code of one function is
completely insulated from the other functions.

Every function interfaces to the outside world in terms


of how information is transferred to it and how results
generated by it are transmitted back. This interface is
specified by the function name. For example, look at Figure
4.1 which explains how the main() function calls another
function to perform a well-defined task.

funcl1()
{
Statement Block;

Otte

- acanekd

Figure 4.1 The main() function calls func1 ()

Generated with https://kome.ai


From the figure we can see that main () calls a function
named funci (). Therefore, main () is knownas the calling

function and funci() is known as the called function. The


moment the compiler encounters a function call, instead of
executing the next statement in the calling function, the
control jumps to the statements that are part of the called
function. After the called function is executed, the control
is returned back to the calling function.

It is not necessary that the main() function can call


only one function, it can call as many functions as it wants
and as many times as it wants. For example, a function
call placed within a for loop, while loop, or do-while
loop can call the same function multiple times until the
condition holds true.

Another point is that it is not only the main() function


that can call other functions. A function can call any other
function. For example, look at Figure 4.2 which shows one
function calling another, and this function in tum calling
some other function. From this we see that every function
encapsulates a set of operations and when called it retumms
information to the calling function.

4.1.1 Why are Functions Needed?

Let us analyse the reasons for segmenting a program


into manageable chunks as it is an important aspect of
programming,

| 106 | Programming in C

main() funel()

{{

funel () ; fune2();
return 0; return:

Figure 4.2 Functions calling another functions

Generated with https://kome.ai


* Dividing a program into separate well-defined
functions facilitates each function to be written and
tested separately. This simplifies the process of getting
the total program to work. Figure 4.3 shows that the
main() function calls other functions for dividing the
entire code into smaller sections (or functions). This
approach is referred to as the top-down approach.

Main function

Function A | Function C |

|
Function B1 | iaien B2

Figure 4.3. Top-down approach of solving a problem

Function B |
ae

e Understanding. coding, and testing multiple separate


functions are far easier than doing it for one big function.

e If a big program has to be developed without the use


of any function other than main() function, then there
will be countless lines in the main() function and
maintaining this program will be very difficult. A large
program size is a serious issue in micro-computers
where memory space is limited.

© All the libraries in C contain a set of functions that the


programmers are free to use in their programs. These
functions have been pre-written and pre-tested, so the
programmers can use them without worrying about their
code details. This speeds up program development, by
allowing the programmer to concentrate only on the
code that he has to write.

« When a big program is broken into comparatively


smaller functions, then different programmers working
on that project can divide the workload by writing
different functions.

Generated with https://kome.ai


func2() func3()

({
― Bae
opt return;
return; )

e Like C libraries, programmers can also write their


functions and use them at different points jn the
main program or in any other program that needs jp,
functionalities.

Consider a program that executes a set of instructions


repeatedly n times, though not continuously. In case the
instructions had to be repeated continuously for n times,
they can be placed within a loop. But if these instructions
have to be executed abruptly from anywhere within the
program code, then instead of writing these instructions
wherever they are required, a better idea is to place these
instructions in a function and call that function wherever
required. Figure 4.4 explains this concept.

Figure 4.4 Function funci() called twice from main ()

4.2 USING FUNCTIONS

In the second chapter we have discussed that when we


execute a C program, the operating system calls the
main() function of the program which marks the entry
point for the execution. When the program is executed, the
main() returns some value to the operating system.

Any function (including main()) can be compared


to a black box that takes in input, processes it, and then
produces the result. However, we may also have a function
that does not take any inputs at all, or the one that does not
return anything at all.

While using functions we will be using the followin

Generated with https://kome.ai


ul
terminologies: ;

e Afunction f that uses another function 8 is known as th

Re . 8 the
calling function and gq is known as the
The inputs thata function t

parameters

called function,

akes are known as arguments/

When a called function returns some result back to the


calling function, it is said to return that result

The calling function may or may not pass parameters


to the called function. If the called function accepts

arguments, the calling function will Pass parameters


else it will not do so. ;

Function declaration is a declaration statement that


identifies a function with its name, a list of arguments
that it accepts, and the type of data it returns,

Function definition consists of a function header


that identifies the function, followed by the body of

the function containing the executable code for that


function.

4.3 FUNCTION DECLARATION/


FUNCTION PROTOTYPE

Before using a function, the compiler must know about


the number of parameters and the type of parameters that
the function expects to receive and the data type of the
value that it will return to the calling function. Placing
the function declaration statement prior to its use enables

Generated with https://kome.ai


the compiler to make a check on the arguments used while
calling that function.

The general format for declaring a function that accepts


some arguments and returns some value as a result can be
given as:

returndatatype functionname(datatype
variablel, data_type variable2,...);

Here, function_name is a valid name for the function.


Naming a function follows the same rules as naming
variables. A function should have a meaningful name that
must specify the task that the function will perform. The
function name is used to call it for execution in a program.
Every function must have a different name that indicates
the particular job that the function does.

return data_type specifies the data type of the value


that will be returned to the calling function as a result of
the processing performed by the called function.

Functions | 107 |

data type variablel, datatype variable2,


is a list of variables of specified data types. These variables
are passed from the calling function to the called function.
They are also known as arguments or parameters that the
called function accepts to perform its task. Table 4.1 shows
examples of valid function declarations in C.

Table 4.1 Valid function declarations

Function declaration

Use of the function

Return data type

char convertto
uppercase (char ch);

Generated with https://kome.ai


Converts a character to upper case.
The function receives a character as
an argument, converts it into upper
case and returns the converted

character back to the calling |

function.

Function name

float avg (int a, int b);

Calculates average of two integer


numbers a and b received as
arguments. The function returns a
floating point value. |

int find_largest (int

Finds the largest of three |


numbers— a, b, and c received as

(float a, float b);

— Variable 1

a, int b, int c);


arguments. An integer value which
Data type of is the largest of the three numbers
variable is returned to the calling function.
double multiply Multiplies two floating point

numbers a and b that are received


as arguments and returns a
double value.

void swap
(int a, int b);

Swaps or interchanges the value of


integer variables a and b received

Generated with https://kome.ai


as arguments. The function returns
no value, therefore the return type
is void.

void print(void);

The function is used to print


information on screen. The
function neither accepts any
value as argument nor returns
any value. Therefore, the return
type is void and the argument list
contains void data type.

Things to remember about function declaration:

Programming Tip:
Though optional,

use argument names


in the function
declaration.

e After the declaration of every

function, there should be a


semicolon. If the semicolon
is missing, the compiler will
generate an error message.

¢ The function declaration is global.

Therefore, the declared function


can be called from any point in the
program.
| 108 | Programming in C

e Use of argument names in the function declaration


statement is optional. So both declaration statements

are valid in C.
int func(int, char, float);

Generated with https://kome.ai


or
int func(int num, char ch, float frum) ;

eA function cannot be declared within the body of


another function.
e A function having void as its retum type cannot retum
any value
e A function having void as its parameter list cannot
accept any value. So the function declared as
void print (void) ;
or
void print ()
does pot accept any input/arguments from the calling
functon
e if the function declaration does not specify any return
type, then by default, the function returms an integer
value. Therefore when a function is declared as

sum{int a, int b);

Then the function sum accepts two integer values from


the calling function and in tum retums an integer value
to the caller.

e Some compilers make it compulsory to declare the


function before its usage while other compilers make
i optional. However, it is a good practice to always
declare the function before its usage as it allows error
checking on the arguments in the function call.

4.4 FUNCTION DEFINITION

When 2 function is defined, space is allocated for that


function in the memory. A function
Programming Tip: § definition comprises two parts:
it is an error to

© Function header

place 2 semicolon i
after the function ¢ Function body

Generated with https://kome.ai


header in the The syntax of a _ function

function definition. definition can be given as:

return data type function name (data type


variablel, data type variable2,...)

statements

return (variable) ;

The number of arguments and the order of argume, ;


the function header must be same as that given sin
function declaration statement. Y the

While return aii


type function _ name (dat,
type variablel, data
variable2,..) is known ve pe
function header, the rest of .
portion comprising of Progra ¢
statements within { } is the ty
tion body which contains the a vs

to perform the specific task. .

The function header is same as function declaration


The only difference between the two is that a function
header is not followed by a semicolon. The list of variables
in the function header is known as the formal Parameter
list, The parameter list may have zero or more Parameters
of any data type. The function body contains instructions
to perform the desired computation in a function,

The function definition itself

Programming Tip:
The parameter

Generated with https://kome.ai


list in the function
definition as well as
function declaration
must match,

Programming Tip: = can act as an implicit function


Afunction can declaration. So the programmer
be defined either may skip the function declaration
before or after statement in case the function is
main().

defined before being used.

The argument names in the function declaration and


function definition need not be the same. However,
the data types of the arguments specified in function
declaration must match with that given in function
definition.

4.5 FUNCTION CALL

The function call statement invokes the function. When


a function is invoked the compiler jumps to the called
function to execute the statements that are part of that
function. Once the called function is executed, the program
control passes back to the calling function.

Function call statement has the following syntax:

function_name(variablel, variable2, ...);

When the function declaration is present before the


function call, the compiler can check if the correct number
and type of arguments are used in the function call and the
returned value, if any, is being used reasonably.

Function definitions are often placed in separate header


files which can be included in other C source files that
wish to use these functions. For example, the header file
stdio.h contains the definition of scanf and printf
functions, We simply include this header file and call these

Generated with https://kome.ai


functions without worrying about the code

functionality ‘0 implement


their Tul =

ust of variables used in function call is known as actual

parameter list. The actual parameter list may contain


variable names, expressions, or constants,

4.5.1 Points to Remember While Calling


Functions

The following points are to be kept in mind while calling


funchons:

e Function name and the number and type of arguments


in the function call must be same

Programming Tip: as that given in the function


A logical error will declaration and function header of
degenerated ifthe the function definition.

arguments in the

aes
athe fun ore than what
pa It is specified to accept then
the extra arguments will be

discarded.

e Ifthe parameters passed to a function are less than what


it is specified to accept then the unmatched arguments
will be initialized to some garbage value.

« Names (and not the types) of variables in function


declaration, function call, and header of function
definition may vary.

¢ If the data type of the argument passed does not match

Generated with https://kome.ai


with that specified in the function declaration then either
the unmatched argument will be initialized to some
garbage value or a compile time error will be generated.

* Arguments may be passed in the form of expressions


to the called function. In such cases, arguments are first
evaluated and converted to the type of formal parameter
and then the body of the function gets executed.

* The parameter list must be separated with commas.

* Ifthe return type of the function is not void, then the value
returned by the called function may be assigned to some
variable as shown in the following statement.

variable name = function_name(variablel,

variable2, ...);

Let us now try writing a program using function.

1. Write a program to add two integers using functions.


#include <stdio.h>
// FUNCTION DECLARATION

Functions | 109 |

int sum(int a, int b);


int main()
{
int numl, num2, total = 0;
printf ("\n Enter the first number: ");
scanf ("%d", &numl) ;
printf ("\n Enter the second number:
scanf ("%d", &num2) ;
total = sum(numl1, num2) ;
// FUNCTION CALL
printf("\n Total = %d", total);
return 0;

Generated with https://kome.ai


// FUNCTION DEFINITION
int sum (int a, int b) // FONCTION HEADER
{ // FUNCTION BODY
int result;
result = a + b;
return result;

Output

Enter the first number: 20


Enter the second number: 30
Total = 50

The variables declared within the function and its


parameters are local to that
function. The programmer may

‘ use same names for variables in

void as the return : é : s


other functions. This eliminates

type when the " Oe. ;

function is expected € need for thinking and keeping

toreturnavalueto Mique names for variables

the calling function. declared in ail the functions in the


program.

In the sum() function, we have declared a variable


result just like any other variable. Variables declared
within a function are called automatic local variables
because of two reasons.

First, they are local to the function. So, their effect (in
terms of scope, lifetime, or accessibility) is limited to

Generated with https://kome.ai


the function. Any change made to these variables is
visible only in that function.

¢ Second, they are automatically created whenever the

function is called and cease to exist after control exits


the function,

A function cannot be used on the left side of an


assignment statement, Therefore writing, func (10) =—

100; is invalid in C, where func is a function that accepts


an integer value, :

Programming Tip:
It is an error to use
the execution
calling function.
the program
on at the point
on call. Refer Figure
rom the called function
ng function when the
nent is encountered.
return statement may or may
retum a value to the calling
function. The syntax of return
‘statement can be given as
return <expression>;
on is placed in between angular
specifying an expression is optional.

return value of the function is undefined.

The expression, if present, is converted to the type


returned by the function. A function that has void as
its return type cannot return any value to the calling
function. So in a function that has been declared with
retum type void a return statement containing an
expression generates a warning and the expression is not
evaluated.

Generated with https://kome.ai


For functions that have no return statement, the
contro! automatically returns to the calling function after
the last statement of the called function is executed. In
other words an implicit return takes place upon execution
of the last statement of the called function, and control
automatically returns to the calling function.

Note

The programmer may or may not place the expression in


@ return statement within parentheses.

By default, the return type of a function is int.

A function may have more than one return statement. For


example, consider the program

Programming Tip: .

en below.
When the value said ai
returned by a #include <stdio.h>
functi ‘ j #include <conio.h>

» int check_relation(int a,

to a variable, then ae
the returned value int main()
isconvertedtothe {
type of the variable int a=3, b=5, tes;
receiving it. elrser();

res = check relation(a, b);

if(res==0) // Test the returned va),,,


printf ("\n EQUAL") ; 2
if (res==1)
printf("\n a is greater than b"),
if (res==-1)
printf("\n a is less than b"),
getch () ;
return 0;

Generated with https://kome.ai


}
int check_relation(int a, int b)

Programming Tip: if (a==b)


An error is return 0;
generated when else if (a>b)
the function does return 1;
not return data of ae

return -1;

Output
a is less than b

In the above program there are multiple return


statements, but only one of them will get executed
depending upon the condition. The return statement

like the break statement, is used

Programming Tip: to cause a premature termination


A function that of the function.

does not return An expression appearing in a


any value cannot return statement is converted to
be placed on the return type of the function in
the right side of which the statement appears. If no
the assignment implicit conversion is possible, the
operator. return Statement is invalid. Since

the return type of the function


check _relation() is int, so the result either 0, 1, or
-1 is evaluated as an integer.

We have mentioned earlier that the variables declared


inside the function cease to exist after the last statement
of the function is executed. So how can we return the
value of sum to the program that adds two integers using a
function? The answer to this question is that a copy of the
value being returned is made automatically and this copy

Generated with https://kome.ai


is available to the return point in the program.

4.6.1 Using Variable Number of Arguments

Some functions have a variable number of arguments


and data types that cannot be known at the compile time.
Typical examples of such functions include the printf ()
an

Generated with https://kome.ai

You might also like