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

Chapter 2 Functions

This document is a course outline on functions in C programming, emphasizing the importance of modular programming by breaking down complex problems into manageable sub-tasks. It covers the definition, advantages, creation, and use of functions, including their declaration, definition, and the distinction between global and local variables. The document also provides examples of function definitions and their calls, highlighting the significance of proper parameter handling and variable scope.
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 views10 pages

Chapter 2 Functions

This document is a course outline on functions in C programming, emphasizing the importance of modular programming by breaking down complex problems into manageable sub-tasks. It covers the definition, advantages, creation, and use of functions, including their declaration, definition, and the distinction between global and local variables. The document also provides examples of function definitions and their calls, highlighting the significance of proper parameter handling and variable scope.
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

National Higher School of Technology and Engineering Annaba

Department of preparatory classes Computer Science 2 Course


First Year 2025/2026

Chapter 2. Functions
So far, the programs we've seen are simple programs with a small number of instructions. These instructions
can easily be grouped into a single block without major issues. For more complex problems, it is strongly
advised not to group all the instructions into a single block. It is more desirable to break down the problem
into a set of sub-problems or sub-tasks, and to program these sub-tasks as independent blocks or modules.
This is the concept of modular programming, which utilizes subprograms.

The C language, like most programming languages, is a modular language. It offers us the possibility to
distribute our programs into several source files and to break down each source file into several modules or
subprograms. In the C language, there is only one kind of subprogram: functions. So far, we have only created
one function in our programs, which is the main() function present in all C programs and is always executed
first. We have also used two predefined functions for reading and writing, namely: the scanf() function and
the printf() function.

In this chapter, we will present the advantages of modularity, discover how we can define and use our own
functions, and explore the main predefined functions of the C language.

1. Modularity and Its Advantages


Most programming languages allow us to subdivide our programs into simpler and more compact
subprograms, functions, or procedures. Using these structures, we can modularize our programs to achieve
more elegant and efficient solutions.

1.1. Modules: A module refers to "a data and instruction entity that provides a solution to a (small) well-
defined part of a more complex problem." A module can call other modules, pass data to them, and receive
data in return. The set of interconnected modules must be able to solve the overall problem.

1.2. Advantages of Modularity: Modularity offers significant advantages during program development. The
main advantages are as follows:

 Better readability: Each module contains only a part of the source code to perform a well-determined
processing.
 Memory space saving and development time: By separating repeated instructions (in a separate
function) from the program body and calling these instructions (which only appear once) whenever
needed, instead of repeating the corresponding code as many times as necessary.
 Decreased risk of errors: Compared to reprogramming code snippets each time.
 Selective testing capability: Individual modules can be tested to ensure their proper functioning.
 Method concealment: When using a module, one only needs to know its effect without having to deal
with the details of its implementation.
 Reuse of existing modules: It is easy to use modules that have been written by oneself or developed
by others.
 Maintenance simplicity: A module can be changed or replaced without affecting other modules in
the program.
 Facilitation of teamwork: A program can be developed by a team by delegating the programming of
modules to different individuals or groups. Once developed, the modules can constitute a common
working base.
 Module hierarchy: A program can first be solved globally at the main module level. Details can be
deferred to subordinate modules, which can also be subdivided into submodules and so on. This way,
we obtain a hierarchy of modules.

Dr Lachtar 1
National Higher School of Technology and Engineering Annaba
Department of preparatory classes Computer Science 2 Course
First Year 2023/2024
2. What is a Function?

Functions are the basic building blocks of the C language. A function is a "portion of a program forming a
homogeneous whole, intended to perform a certain well-defined task."

The main purpose of a function is to return a result after executing several associated instructions. For a
function to execute properly, it generally receives what are called arguments (or parameters) as input. Once
these parameters are received, the function executes and returns a final result. It is said that in its general form,
a function receives inputs and returns outputs. The following figure schematically represents a function.

. .
Inputs . .
. Outputs
. Function

For example, the function that calculates the sum of two numbers has 2 inputs, one output, and can be
schematically represented as follows:

a a+b Output
Inputs Function
b sum

Notes :
 From what has been discussed, a function in C is quite close to its corresponding mathematical notion.
 It's possible for a function to receive no arguments as input.
 Some functions receive information but do not return anything (for example, printf). In this case,
these functions are said to return void. Some others may return a set of values (like the scanf
function).

Properties:

 A function in the C language can modify global data. This data resides in a memory area that can be
modified by the rest of the program.
 A function is characterized by a call and a return:
o The call is made by the main program main() or another function.
o The return occurs after the last action of the called function, and the program continues just
after the function call.
 The main program main() and functions need to communicate values. During a function call, the
values passed are the input parameters, and at the end of a function, the returned parameters are the
output parameters. Thus, a function allows performing the same processing on different sets of
variables. For example, the sum function can return the sum of any two numbers received as input.

Dr N. lachtar 2
National Higher School of Technology and Engineering Annaba
Department of preparatory classes Computer Science 2 Course
First Year 2023/2024
Main Program Function1 Function2
Instruction 1 Instruction 1 Instruction 1
. Call
Instruction 2 Call Instruction 2
Call Function 1 . .
Instruction n Call Function2 .
. Instruction n .
. Return . .
Return
Return Return

3. Creation and Use of Functions


When defining or using functions, they are distinguished from variables by the presence of opening and
closing parentheses.

3.1. Declaration and Definition of a Function

The declaration of a function consists of announcing that a certain identifier corresponds to a function, which
returns a certain type, and which receives certain parameters.

The definition of a function is a declaration where, additionally, the code of the function itself is provided.

3.1.1. Function Definition

The definition of a function takes the following form:

return_type function_name(type_1 arg_1, ..., type_n arg_n)


{
Local variable declarations
List of instructions
}

The first line of this definition is the function header. In this header, function_name is the name of the
function, and return_type denotes the type of the function, which is the type of the value it returns. The
header also indicates, within parentheses, the list of argument declarations separated by commas. The function
arguments are called formal parameters, as opposed to actual parameters, which are the parameters with which
the function is actually called. Their identifiers (names) are only significant within the function. If the function
has no parameters, the parameter list can be declared as (void) or simply as (). Note that the names of the
formal parameters and the function are identifiers, so they must adhere to the restrictions defined in the
previous chapter, section 3.1.

The rest of the definition corresponds to the body of the function. It is a block containing the instructions that
will be executed when the function is called, and possibly declarations of data (constants and variables) local
to the function.

Remarks:

 Note that there is no semicolon behind the ) in the header. The presence of a semicolon at this point
would cause errors.

Dr N. lachtar 3
National Higher School of Technology and Engineering Annaba
Department of preparatory classes Computer Science 2 Course
First Year 2023/2024
 It is not allowed to "factor out" a common type for several arguments. Each argument must be preceded
by its type. For example, double sum(double a, b) is not allowed. The type of each argument must
be specified: double sum(double a, double b).
 Unlike in other languages, in C, one cannot define a function inside another: all functions are at the
same level, i.e., global.
 It is possible to use a function before its definition as long as it is declared beforehand.
 In principle, the order of definitions in the program text does not matter, but each function must be
declared or defined before being called.

3.1.2. Function Declaration: The declaration of a function is done through a prototype that indicates only the
name of the function and the type of data returned and received by the function. It corresponds to the header
of the function definition followed by a semicolon ";".

3.1.3. Function and Argument Types: Formal parameters can be of any type. However, a function can only
provide as a result:

 A numeric type: short, int, long, float, double, long double.


 A character: char type.
 A structure: struct.
 A pointer (Chapter 5).

If a function does not return a result, void (which means empty) must be indicated as the result type. Finally,
if the type of the function is not indicated, the compiler assumes it is a function with an integer result (of
type int). For example, the following headers are correct:
double somme(double a, double b)
int nbPos()
void affichage(char c)

Remark:

Functions that do not return a result and do not receive inputs are generally used to structure a program. Instead
of writing thousands of lines in the main program main(), it is better to gather them in functions.

3.1.4. The return Statement: A function declared as having a return type other than void must return
something. To do this, we use the return statement to return control to the calling function. The list of
instructions in the function body must contain at least one return statement whose syntax is:

return expression ou return (expression)

When the return statement is executed, expression is evaluated, and control is returned to the caller of the
function by returning the value of expression. The value of expression is the value returned by the function.
Its type must therefore be the same as that specified in the function header.
Example: To create a function that returns the value 5, we write the following definition:
int fonction5(){
return 5; //rend le contrôle au bloc appelant en renvoyant la valeur 5
}

Remarks:

Dr N. lachtar 4
National Higher School of Technology and Engineering Annaba
Department of preparatory classes Computer Science 2 Course
First Year 2023/2024
 If the function does not return a value (void type function), the return statement is optional: once it
reaches the end of the function, it will return to the caller, even if there is no return statement.
 Multiple return statements can appear in a function. Returning to the calling program will then be
caused by the first return encountered during execution.
 The return statement is like any other instruction, so it is possible to use as many as desired in the body
of a function. For example, in a function that returns the maximum of 2 numbers a and b, we can write:
if(a>b) return(a); else return(b);

3.1.5. Examples of Function Definitions

 The inverse function returns the inverse of a real number passed as input:

double inverse(double n){ // inverse function header


int inv = -n; // declaration and calculation
of the inverse
return inv; // return the result
}

 The power function takes two integer numbers as input and returns the power of these two numbers:

int power(int x, int y){ // power function header


int p = 1, i; // declaration of 2 local variables
for(i = 0; i < y; i++)
p *= x; // loop calculating the power
return p; // return the power
}

 The PI function returns a real value equal to 3.14 and does not receive any input parameters:

float PI(void){ // PI function header


return 3.14; // return the value 3.14
}

 The display function displays a message on the screen. It returns nothing and does not take any input
parameters:

void display(){ // display function header


printf("Hello"); // display a message
}

 The nbPos function returns the number of positive values in an array of 10 real elements passed as
parameters:

int nbPos(double t[10]){ // nbPos function header


int nb = 0, i; // declaration of 2 local variables
for(i = 0; i < 10; i++) // calculation of the number of positive values
if(t[i] > 0) nb++;
return nb; // return the result
}

3.2. Function Call: Calling a function directs the main program or another function to execute the function.
The call is made by specifying the name of the called function and giving a list of expressions within
parentheses corresponding to the calling values of the various formal parameters of the function. If the called
function returns a value, the assignment of the output variable is also given. The syntax of the call is as follows:

Dr N. lachtar 5
National Higher School of Technology and Engineering Annaba
Department of preparatory classes Computer Science 2 Course
First Year 2023/2024
nom_fonction(expr_1,expr_2,…,expr_n); ou
variable=nom_fonction(expr_1,expr_2,…,expr_n);

The expressions within parentheses are evaluated, then passed as actual parameters to the function
function_name, which is then activated. The value returned by the function (if any) is assigned to variable.
Example: An example of calling and using the result of the power function (described above) in the main()
function is as follows:

main(){
int a, b, r;
printf("Enter 2 integers: ");
scanf("%i%i", &a, &b);
r = power(a, b);
printf("The power is %i", r);
}

Remarks:

 In the case of a function without parameters, the list of expressions must be empty; it is not possible
to use the keyword void as an actual parameter. For example, the call: float d = PI(void); is an
incorrect call to the PI function described earlier.
 The order and type of the actual parameters of the function must match those given in the function
header (the formal parameters).
 Actual parameters can be expressions, constants, or variables.

3.3. Scope and Lifetime of Variables: Variables in the C language do not all have the same lifetime. There
are permanent variables occupying a memory location that remains the same throughout the execution of the
program, and temporary variables occupying a memory location dynamically during program execution. The
part of memory containing permanent variables is called the data segment. However, temporary variables are
located in the part of memory called the stack segment. Indeed, the lifetime of variables is linked to their
scope, i.e., the portion of the program in which they are defined. We distinguish between global variables and
local variables.

3.3.1. Global Variables: A variable declared outside of any function, including the main() function, is called
a global variable. Global variables are known to the compiler throughout the portion of code that follows their
declaration. They are modifiable and accessible by all functions without the need to pass them as parameters.
Their scope (or validity space) is global. Note that global variables are always permanent.

3.3.2. Local Variables: A variable declared inside a function (or a block of instructions) of the program is
called a local variable. By default, local variables are temporary. Their lifetime is limited to the execution of
a function, and their scope is limited to that function. Thus, when a function is called, it places its local
variables on the stack. At the exit of the function, local variables are popped from the stack and thus lost.
Local variables can only be modified and accessed within the function where they are declared. To modify or
use them in another function, it is necessary to pass them as parameters.

Remark: Local variables in a function have no particular connection to global variables with the same name
or local variables in another function with the same name.

3.3.3. Example of Global and Local Variables:

Dr N. lachtar 6
National Higher School of Technology and Engineering Annaba
Department of preparatory classes Computer Science 2 Course
First Year 2023/2024
int p = 0, s = 0; // declarations of global variables
int sum(int a, int b) // function sum header
{
int s, c; // declarations of local variables within the sum function
s = a + b; // modification of the local variable s
c = a - b; // modification of the local variable c
p = a * b; // modification of the global variable p
return s;
}

int main(){
int x, y; // declarations of local variables within main
scanf("%i%i", &x, &y);
int c = sum(x, y);
printf("The sum is %i", c);
printf("The content of the global variable s is %i", s);
printf("The content of the global variable p is %i", p);
return 0;
}
In this example, two global variables p and s have been declared. Unlike the variable s, which has not been
changed, the variable p has been used and modified in the sum() function. The sum() function returns the sum
s of two integers received as input, calculates the difference of these two numbers in a local variable c, and
their product in the global variable p.
The sum function is called within main() and its result is assigned to a local variable c.
However, two variables named c have been declared; one in the main() function and the other in the sum()
function. These two variables have nothing to do with each other even though they have the same name.
Similarly, the local variable s declared in the sum() function has no connection with the global variable of the
same name.

3.4. Parameter Passing: Function parameters are treated in the same way as local variables: when a function
is called, the actual parameters are copied into variables created in the stack segment. These variables are
internally accessible by the function from the corresponding formal parameters. The function then works only
on the copy of the actual parameters. This copy disappears upon returning to the calling program. This implies,
in particular, that if the function modifies the value of one of its parameters, only the copy will be modified;
the variable in the calling program will not be modified. It is said that the parameters of a function are passed
by value.

Example:

void permutation(int a, int b){


int c = a;
a = b;
b = c;
}

Dr N. lachtar 7
National Higher School of Technology and Engineering Annaba
Department of preparatory classes Computer Science 2 Course
First Year 2023/2024
int main(){
int a = 3, b = 5;
permutation(a, b);
printf("a=%i, b=%i", a, b);
return 0;
}

The above program prints "a=3, b=5". This shows that the initial value of the variables a and b has not been
changed because the permutation() function only modified a copy of these variables.

Remark: For a function to modify the value of one of its arguments, it must have the address of that object as
a parameter, not its value. This passing of arguments is called pass by reference.

4. Standard Function Libraries


Every C compiler comes with a set of standard function libraries. A library is a collection of tested and
archived functions to be reused. Some functions are essential because they allow performing tasks that would
be impossible without them (such as the scanf() and printf() functions). Others serve to relieve the programmer
by sparing them from writing long and tedious algorithms. C libraries are available in their precompiled form
(extension: ".lib"). To use them, you need to include header files (extension ".h") in your programs. These
files contain prototypes of the functions defined in the libraries and create a link between the precompiled
functions and our programs. Including header files is done using the #include directive as described in the
previous chapter.
There are several C libraries that are considered standard because they are found in most compilers. The main
function libraries of the C language are as follows:
4.1. The Input-Output Library: The function declarations are in the header file <stdio.h>. They handle input
and output, whether from files or the keyboard. The main standard functions for keyboard and screen are:

Functions Description
getchar() Character input
putchar() Character output
printf() Formatted output
scanf() Formatted input
gets() String input
puts() String output
4.2. Character Manipulations The function declarations are in the header file <ctype.h>. They deal with
processing characters. The main functions are:
Functions Description
Isalnum() Test letter or digit
isalpha() Test uppercase or lowercase letter
iscntrl() Test control character
isdigit() Test decimal digit
isxdigit() Test hexadecimal digit
isprint() Test printable character
ispunct() Test punctuation
isspace() Test word separator
isupper() Test uppercase letter
islower() Test lowercase letter

Dr N. lachtar 8
National Higher School of Technology and Engineering Annaba
Department of preparatory classes Computer Science 2 Course
First Year 2023/2024
toupper() Conversion to uppercase
tolower() Conversion to lowercase

All these functions, except the last two, take a char as input and return an int (the value 1 if the character
satisfies the property and 0 otherwise). The last two functions take a char as input and return a char
corresponding to its lowercase or uppercase.

4.3 String Manipulations: The function declarations are in the header file <string.h>. They deal with
processing strings of characters.

Functions Description
strcat() Concatenation of two strings
strcmp() Comparison of two strings
strcpy() String copy
strlen() String length
Strncat Character concatenation
strncmp() Comparison within length
strncpy() Copy of n characters
sscanf() Formatted reading into a string
sprintf() Formatted copy into a string

4.4 Mathematical Functions: The function declarations are in the header file <math.h>. They deal with
processing numbers. Note that the result and parameters of all these functions are of type double.

Functions Description
acos() Arc cosine
asin() Arc sine
atan() Arc tangent
ceil() Ceiling (smallest integer greater than or equal to)
cos() Cosine
cosh() Hyperbolic cosine
exp() Exponential
fabs() Absolute value of a real number
floor() Floor (largest integer less than or equal to)
fmod() Remainder of real division
log() Natural logarithm
log10() Decimal logarithm
pow() Power
sin() Sine
sinh() Hyperbolic sine
sqrt() Square root
tan() Tangent
tanh() Hyperbolic tangent

4.5. Various Utilities: The function declarations are in the header file <stdlib.h>. Some of them include:

Dr N. lachtar 9
National Higher School of Technology and Engineering Annaba
Department of preparatory classes Computer Science 2 Course
First Year 2023/2024

Function Action
atof() converts a string to a double
atoi() converts a string to an int
atol() converts a string to a long int
rand() provides a pseudo-random
abs integer absolute value of an int
labs absolute value of a long int
The first three functions accept a character string as input and return a double, int, and long int, respectively.
The rand() function doesn't accept any input parameters and returns a pseudo-random integer. The abs() and
labs() functions accept an int and a long int as input, respectively, and return an int and a long int, respectively

Dr N. lachtar 10

You might also like