Vous êtes sur la page 1sur 11

C & DS for I MCA Unit-3 VVIT

Functions
A function is a self-contained block of statements that perform a coherent task of some
kind. Functions can be sometimes called sub-routines or sub-modules, etc. A C program can be
thought of as a collection of these functions. C supports divide and conquer with usage of
functions as different tasks of the program can be well organized with various functions.

Any C program contains at least one function called main(). Use of main() function in any C
program is mandatory. The C compiler starts the program execution by calling the main function.

There can be any number of other user-defined function apart from main(). These functions are
called directly or indirectly from the main function. After execution of the function body, the
control returns to the location where it is called. Therefore when end of main() function (which
is called by compiler) is reached, program will terminate.

A function once defined can be called at multiple locations when ever needed. There use of
functions increase re-usability.

Functions can be broadly classified into 2 types:


1. Built-in Functions (or Pre-defined functions or Library functions)
2. User-defined functions

Built-in functions are pre-defined in C library and are ready to use. They are categorized into
different header files (with extention .h). C language has rich set of built-in functions and so it is
called a robust. To use any built-in function we just need to include the corresponding header
file using the preprocessor directive #include and call it by sending the arguments (or
parameters) that it needs as input.
Eg: printf(), scanf(), getch(), clrscr(), random(), abs(), fabs(), gets(), puts(), etc.

The general form of declaring and defining a function is as follows:


data_type function_name(parameter-list)
{
function-body();
.
.
return (exp);
}
Where, “data_type” (often called return type) is the type of the value that the function can return,
function_name can be any unique identifier (name). The function name should be unique and
therefore no two functions in program can have same name. The ‘parameter-list’ is the list of
parameters (also called arguments) that are to be send while calling the function. The “function-
body” is the set of statement that are executed when the function is called. These statements are
used to achieve the specific task that the function is intended for.

Staff: Janaki Ram Dept of IT and CSE Page:1


C & DS for I MCA Unit-3 VVIT

Using (calling) a function:

A function that is defined can be used (called) by another function. The calling function
should declare the function that it wants to use if the called function is not defined before it.
While declaring so, it should not specify the function body. This is called function signature. In
other words if a function return type, name and parameter list are specified without specifying its
body, then it is called function signature.

Any C function by default returns int and therefore use of such does not need the explicit
declaration in the calling function. It is implied.

Passing values to functions:

The mechanism used to convey information to the function (input to function) is by


sending arguments (or parameters). The list of arguments that the function can accept should be
defined during the function definition. These arguments are called formal arguments. These are
local to the function and can be used only inside the function definition. Multiple parameters are
separated by commas.

When a function (often the main()) calls other function then it has to pass the values to
the arguments of the called function. These are arguments are called actual arguments.

Actual arguments carry forward the values to formal arguments and any change to the
formal arguments will not affect the values of actual arguments in the called function. This type
of function call is called “call by value”. If the pointers are used in the parameter list then the
calling function should send the address of the variable instead of the value, this is called “call by
reference”. Since the addresses of the variables are sent as arguments, any change to the value of
the arguments will affect the same in called function. This will be referred again in Unit-IV with
examples.

The return statement:

The return statement can be used for 2 purposes. They are:

return; To simply return the control to the called function.

return (exp); To return the control to the called function along with value of the exp.

Simple return statement is used in functions whose return type is specified as void (no values).

The second type return (exp) is used when the function as to return some value. The
expression (exp) followed by the return keyword can be a constant or a variable or any complex
expression. The type of the value of the expression should match with return type specified in
the function declaration. Only one value can be returned using a return statement.

Staff: Janaki Ram Dept of IT and CSE Page:2


C & DS for I MCA Unit-3 VVIT

If a return type is not specified in function definition then by default the function returns
int. Therefore such kind of function should return any integer value.

There cannot be multiple returns statements in a function until unless each of the return
statement falls into a different code section that are divided based on conditional logic. If 2
return statements, exist without any condition then the second return statements code can never
be reached (code has no effect) as the control always returns to called function after executing
the first return. Here is a small illustration.

{
if(a%2==0)
return 1;
else
return 0; //this is OK to use.
}

{
return 1;
return 0; //unreachable code and this not OK to use.
}

Variable scope rule:


• Variable declared inside a function are local to the function and cannot be used in any
other function.
• Variables declared outside all functions (on top of all functions) are called global
variables and can be accessed in all functions of the program.
• If a local variable is declared with the same name as global variable then the local
variable will override the global variable.

Eg: Factorial of a number using a user defined function fact().


main()
{
int n;
long int factorial;
long int fact(int); //declaration of the function factorial which returns a long int
printf("Enter the number to find its factorial: ");
scanf("%d",&n);
factorial=fact(n); //calling the function to find the factorial ( value to parameter should be sent).
printf("The factorial of the given number is : %lf", factorial);
}//end of main

Staff: Janaki Ram Dept of IT and CSE Page:3


C & DS for I MCA Unit-3 VVIT

long int fact(int num) //function to calculate the factorial for a given number
{
long int fact;
int j;
if(num==0) //Zero factorial is 1
return 1;
else if(num<0) //Factorial cannot be calculated for numbers less than zero, so return 0
return 0;
else //For number greater than zero multiply the numbers from one to itself
{
for(j=1;j<=num;j++)
fact*=j; //keep multiplying numbers and save it in fact until the number is reached.
return fact; //returning the calculated factorial
}
}
Note: For more examples refer lab exercises 1c, 2a, 2b,2c, 5b, etc.

Recursion:
If a function calls itself, then it is called Recursion. Recursion is sometimes called
circular definition. This is because using recursion, solution for a problem is defined in terms of
the smaller instances of the same problem.

If a function calls another function which again calls back the first function then also it
results in recursion and in particular called as Indirect Recursion. In other words if a series of
function calls lead to calling of the first function (which actually initiated the function calls) then
it is called Indirect Recursion.

While solving any problem using recursion, enough care should be taken that it will not
result in infinite function calls. Infinite functions can occur when the function calls itself
unconditionally.

Since main() is also a function, recursion can also be applied on main().Care should be
taken that the program should terminate at some point of time (use of static or global variables to
track number of the function calls is one solution).

Eg: The above fact() function can be changed to use recursion as follows:

#include<stdio.h>
long int fact(int num) //function fact() to find the factorial of the given num, should return a long int
{
if(num==0) //factorial of zero is 1

Staff: Janaki Ram Dept of IT and CSE Page:4


C & DS for I MCA Unit-3 VVIT

return 1;
else
return num*fact(num-1); //n! can be represented as n*(n-1)!
}
Note: For more example refer to lab exercise 3

Storage Classes:
The variable declared in C can be qualified by four different storage classes. These
storage classes determine various properties of the variables such as scope, life, default value and
memory in which they are stored.
The four storage classes are as follows:

Type Keyword
Automatic variables auto
External Variables extern
Static Variables static
Register Variables register

Scope of variable defines which part of the program that the variable is accessible.
Longevity or Life refers to the period during which a variable retains a given value during
execution of a program. Life has direct effect on the utility of the given variable. In general
scope and life of all variables will be same (except in case of static variables).
Memory: Variables can be stored in either RAM (primary memory) or CPU’s register memory.
Default value of different variables depends on the storage type used to define them.

At the outset variable can be divided into 2 categories based on the location at which they are
decalred. They are:
Internal Variables (Local Variables)
External Variables (Global Variables)

Internal Variables are the ones that are defined inside any of the functions in the C program.
They can be accessed only within the function body. They cannot be accessed by any other
function. Internal Variable further can be of different types such as auto, static or register.

auto:
 The storage class auto is used for declaring automatic variables that are local a particular
function.
 By default all variables in a function as auto variables therefore explicit usage of auto
keyword while declaring them is not necessary.

Staff: Janaki Ram Dept of IT and CSE Page:5


C & DS for I MCA Unit-3 VVIT

 The scope and life of auto variables is only with the function body that they are defined.
The formal arguments (parameters) of a function are also auto variables.
 The auto variables are created when the function execution starts and are destroyed
(recycled) at the end of the function execution.
 The default value of auto variables is unpredictable and sometimes called as garbage
value.
 All auto variables are stored in the primary memory (RAM).
Eg: double f;
auto double f;

static:
 The storage class auto is used for declaring static variables that are local a particular
function.
 The value of the static variable persists (is retained) among multiple function calls.
 The scope of these variables is only with the function that they are defined.
 The default value of the static variables is 0. If they are explicitly initialized to a different
value, the initialization happens when the function in which they are defined is called for
the first time. For the consecutive calls of the same function the static variables are not
initialized rather the value of the variable in the previous execution of the function is
retained.
 Therefore the scope and life of the static variables are not same. The scope is limited to
only the function body but the life persists among multiple function calls. In other words
as in case of auto variables, the variables are not destroyed after execution of function
body.
 Memory: The static variables are stored in the primary memory (RAM).

Eg:
main()
{
int i;
for(i=0;i<3;i++)
func();
}
func()
{
static int x; //declaration of static variable (default value is zero)
int y=0; //by default this will be auto variable
x++;
y++;
printf(“x= %d, y=%d\n”,x,y);

Staff: Janaki Ram Dept of IT and CSE Page:6


C & DS for I MCA Unit-3 VVIT

}
Output:
x=1, y=1
x=2, y=1
x=3,y=1

register:
 The register variables are same as auto variables except that they are stored in CPU’s
registers.
 Therefore the scope and life of the register variables are limited to the function in
which they are defined.
 The default value of the register variables is unpredicted (or garbage value).
 Memory: They are stored in the CPU registers.
 In general the variable whose value is used many times is stored in CPU registers. By
using this there will not be any time consumed by CPU to get these values from
memory. (fast and easy access)
 Since the register memory is limited, huge number of variables should not be
declared as register variables. Just in case if the CPU is out of register memory then
the variables declared as register are also stored in primary memory and will be
treated as auto variables.

External Variables are the ones which are defined outside any function. Many a times these are
referred as Global variables.
 In general these are defined on top of all the functions in a C program.
 The scope and life of the global variables (or external variables) is the entire program
(they can be accessed in all the functions).
 The default value of the global variables is zero.
 Memory: These are stored in primary memory.

Use of extern key word:


The extern keyword is used to declare the external variables in the functions which do not
have default access to the external variables (global variables). When the variables are declared
using extern, it is just to indicate that the function wants to use a variable declared externally and
so no memory will be allocated for this declaration.
Eg:
main()
{
extern int x; //no memory allocated for extern declaration (main does not have direct access to x
printf(“Display in Main: %d\n”, x);
}

Staff: Janaki Ram Dept of IT and CSE Page:7


C & DS for I MCA Unit-3 VVIT

int x; //external variable declaration memory will be allocated and default value is zero
void disp()
{
x=90; //disp() can directly access x because it is defined after actual declaration of x
printf(“Display in disp: %d\n”,x);
}
Output: Display in Main: 0 //since initial value of x is 0
Display in disp: 90

In case of arrays extern declaration need not specify the array size.
Eg:
main()
{
extern int ar[]; //no memory allocated so size need not be specified.
printf(“Display in Main: %d\n”, x);
}
int ar[5]; //external declaration or global declaration and need to specify size to allocate memory

All functions are by default external (we cannot define any function inside other function).
Therefore declaring the functions in which they are used need not use extern qualifier
specifically. It is implied.
Eg: long int fact(int); is equivalent to extern long int fact(int);

Summary in a Table:

Storage Description Scope Life Memory Default


Class Value
auto By default all variables in a Accessible within For one primary unpredictable
function are automatic. the function that execution of memory (garbage
Declared inside any of the they are defined. the function. (RAM) value)
functions in the program.
static Static variables are generally Within the Life of these primary zero (0)
defined within a function and function that they variables is till memory
value persists among multiple are defined end of program (RAM)
function calls
extern Declared outside all the Can be accessed Till the end of primary zero (0)
functions. in all the the program memory
functions (RAM)
register Similar to auto variables Within the For one register unpredictable
except that they are stored in function that they execution of (garbage
CPU registers. are defined the function. value)

Staff: Janaki Ram Dept of IT and CSE Page:8


C & DS for I MCA Unit-3 VVIT

The C Pre Processor:

Pre Processor is a program that processes the source code before it passes through the
complier. It operates under the control of what is known as preprocessor command lines or
directives. They are generally placed before the main function (in fact before all functions) in the
source program.
All Pre processor directives begin with a ‘#’ symbol and does not require a semi colon at the end.
Following are the preprocessor directives:

#define  Defines a macro substitution.


#include  Specifies the file to be included.
#undef  Undefines a macro previously defined.
#ifdef  Test for a macro definition
#endif  specifies end of #if
#ifndef  whether a macro is not defined.
#if  Test a compile time condition.
#else  specifies alternative when #if test fails.

The pre processor directives can be categorized into three categories:


1. Macro Substitution
2. File Inclusion
3. Compiler Control Directives.

Macro Substitution:
The process in which an identifier in a program is replaced by predefined string
composed of one or more tokens is called Macro Substitution. The definition of the identifier as
string is called Macro Definition (a pre processor directive).
Macros are defined using the preprocessor directive #define.
General Form:
#define identifier string

Macro substitution can be of 2 types:


• Simple Macro Substitution
• Augmented Macro Substitution

Simple Macro Substitution is simply replacing a identifier by the string (or constant) in its
definition. This generally used for defining some predefined constants such as size of arrays,
max length of string, etc. The convention to name macro identifiers is to use all capitals.
Eg: #define COUNT 100
#define MAX_LEN 200.

Staff: Janaki Ram Dept of IT and CSE Page:9


C & DS for I MCA Unit-3 VVIT

#undef can be used to undefine a macro previously defined. While undefining the macro only the
identifier is used (no need of string).
General form: #undef identifier.
This is useful when we want to restrict the definition only to a particular part of the program.
Eg:
#define MAX_SIZE 100 //defining a macro
main()
{
int a[MAX_SIZE]; //this will substituted by the constant before compilation
.
for(i=0; i<MAX_SIZE;i++) //this will substituted by the constant before compilation
.
.
if(k==MAX_SIZE) //this will substituted by the constant before compilation
}
#undef MAX_SIZE
func()
{
int z[MAX_SIZE]; //cannot use macro here as it is already undefined
int x[100]; //this is OK to use
}

File Inclusion:
We can include an existing file into a c program. The file can be user created one or a
header file (from C Library). The pre processor directive #include is used for including a file.

To include header files the file name is specified within a set of angled brackets. This indicated
the preprocessor to search for the file only in the C Library. General form is as follows:
#include<headerfile>
For other files the file name is specified within a set of double quotes. Simply file name is
mention in case it is in the current directory. If it is in a different directory the full path of the file
is given.

#include”filename” //for current directory files


#include”filepath” //for files in other directories

Eg: #include<stdio.h>
#include”QuadraticRoots.c”
#include”D:\LabPrograms\GCD.c”

Staff: Janaki Ram Dept of IT and CSE Page:10


C & DS for I MCA Unit-3 VVIT

Compiler Control Directives (This is out of scope the syllabus and so can be ignored while
preparing for exams):
• These directives are for advanced programmers.
• These are used to give certain directives so as to make the program work in different
types of computer (which may vary with their build or Operating System, etc).
• Conditional compilation can be defined to switch on or off a particular line or group of
lines in a program (depending on the type of computer).

Staff: Janaki Ram Dept of IT and CSE Page:11

Vous aimerez peut-être aussi