Professional Documents
Culture Documents
Unit IV
Functions - defining and accessing a function, function arguments, call by value, call
by reference, calling functions with arrays, external, state and register variables,
scope of variables, local and global variables, type conversion, block structure,
recursion.
=====================================================================
Introduction to Functions
A function is a block of code that performs a particular task. There are times
when we need to write a particular block of code for more than once in our
program. This may lead to bugs and irritation for the programmer.
C language provides an approach in which you need to declare and define a
group of statements once and that can be called and used whenever required.
This saves both time and space.
C functions can be classified into two categories,
Library functions
User-defined functions
Library functions are those functions which are defined by C library, example
printf(), scanf(), strcat() etc. You just need to include appropriate header files
to use these functions. These are already declared and defined in C libraries.
User-defined functions are those functions which are defined by the user at
the time of writing program. Functions are made for code reusability and for
saving time and space.
Advantage of function
o It provides modularity to the program.
o Easy code Reusability. You just have to call the function by its name to
use it.
o In case of large programs with thousands of code lines, debugging and
editing becomes easier if you use functions
Declaration of function
return-type function-name (parameter-list);
A function declaration consists of 4 parts.
1
2
3
4
5
return-type
function name
parameter list
function statement
a return statement
Definition of function
return-type function-name (parameter-list)
{
function-body ;
return statement;
}
Return type
Return type specifies the type of value (int, float, char, double) that
function is expected to return to the program calling the function.
Function name
Function name specifies the name of the function. The function name is
any valid C identifier and therefore must follow the same rule of formation as
other variables in C.
Parameter List
The parameter list declares the variables that will receive the data sent
by calling program. They often referred to as formal parameters. These
parameters are also used to send values to calling program.
Function Body
The function body contains the declarations and the
statement(algorithm) necessary for performing the required task. The body is
enclosed within curly braces { }and consists of three parts.
o Local variable declaration.
o function statement that performs the tasks of the function.
o a return statement that return the value evaluated by the
function.
Functions and Arguments
Arguments are the values specified during the function call, for which
the formal parameters are declared in the function.
The function can be categorized in three forms:o The function with no arguments and no return.
o The function with arguments but no return.
o The function with arguments and return.
4
2
The function declaration order may be different than order of function calling
means function can be called in any order.
//actual argument
Example
fun(5, 6)
fun (5, 2.9, a)
fun (j, k+2, +)
wrong
right
right
//actual argument
//formal argument
Note:
o Return value may be constant, variable or an expression
o The return statements value must be same type of the functions types
o The return statement without value can be used only in void type
functions.
o A single function may have one or more return statements. Whenever
the return statement is executed the control is transferred back to
calling point and the specified value is put there.
a and b are
local to main
ACTUAL
VARIABLE
a and b are
local to print
FORMAL
VARIABLE
Call by Reference
When we pass address of variable to function, it copies value of actual
argument to formal argument.
Example
int add(int ,int);
7
510
void main()
{
int a,b;
tot = add(&a,&b);
4
804
510
804
*a
*b
a and b are
local to main
ACTUAL
VARIABLE
}
int print(int *a,int *b)
{
int c;
c = *a+*b;
return c;
}
*a and *b are
local to print
a & b is pointer
FORMAL
VARIABLE
Syntax
First
//definition
Second
void search(int valsrc, int ap[])
{
.
.
.
}
Example
#include <stdio.h>
/* function declaration */
double getAverage(int arr[], int size);
int main ()
arr
500
500
500
ap
static pointer
return 0;
Function call
fun(a,b)
fun(a,f)
fun(&a,f)
fun(&a,f)
Function Definition
Void fun(int x,int y){}
Void fun(int x,float y){}
Void fun(int *xp,float y){}
Void fun(int *xp,float *yp){}
Recursion
Recursion is a programming technique that allows the programmer to express
operations in terms of themselves. In C, this takes the form of a function that
calls itself. A useful way to think of recursive functions is to imagine them as a
process being performed where one of the instructions is to "repeat the
process"(chaining of function/ Nesting of function).
This makes it sound very similar to a loop because it repeats the same code,
and in some ways it is similar to looping. On the other hand, recursion makes it
easier to express ideas in which the result of the recursive call is necessary to
complete the task. Of course, it must be possible for the "process" to
sometimes be completed without the recursive call.
Recursion is a special case of this process, where a function calls itself.
Example 1
main()
{
printf(We are in Main!);
main();
}
[main() called]
We are in Main!
[main() called]
We are in Main!
[main() called]
We are in Main!
Example 2 Factorial of number
int factorial (int n)
{
if ( n < 0)
return -1; /*Error*/
if (n == 0)
return 1; /*Terminating condition*/
return 0;
return product;
Type Casting
Type casting is a way to convert a variable from one data type to another data
type. For example, if you want to store a long value into a simple integer then
you can type cast long to int. You can convert values from one type to another
explicitly using the cast operator as follows:
(type_name) expression
Consider the following example where the cast operator causes the division of
one integer variable by another to be performed as a floating-point operation:
#include <stdio.h>
main()
{
int sum = 17, count = 5;
double mean;
mean = (double) sum / count;
printf("Value of mean : %f\n", mean );
}
When the above code is compiled and executed, it produces the following
result:
Value of mean: 3.400000
It should be noted here that the cast operator has precedence over division, so
the value of sum is first converted to type double and finally it gets divided by
count yielding a double value.
Type conversions can be implicit which is performed by the compiler
automatically, or it can be specified explicitly through the use of the cast
operator. It is considered good programming practice to use the cast operator
whenever type conversions are necessary.
Integer Promotion
Integer promotion is the process by which values of integer type "smaller" than
int or unsigned int are converted either to int or unsigned int. Consider an
example of adding a character in an int:
#include <stdio.h>
main()
{
int i = 17;
char c = 'c'; /* ascii value is 99 */
int sum;
sum = i + c;
printf("Value of sum : %d\n", sum );
}
When the above code is compiled and executed, it produces the following
result:
Value of sum : 116
Here, value of sum is coming as 116 because compiler is doing integer
promotion and converting the value of 'c' to ascii before performing actual
addition operation.
Usual Arithmetic Conversion
The usual arithmetic conversions are implicitly performed to cast their values
in a common type. Compiler first performs integer promotion, if operands still
have different types then they are converted to the type that appears highest
in the following hierarchy:
The usual arithmetic conversions are not performed for the assignment
operators, nor for the logical operators && and ||. Let us take following
example to understand the concept:
#include <stdio.h>
main()
{
int i = 17;
char c = 'c'; /* ascii value is 99 */
float sum;
sum = i + c;
printf("Value of sum : %f\n", sum );
}
When the above code is compiled and executed, it produces the following
result:
Value of sum : 116.000000
Here, it is simple to understand that first c gets converted to integer but
because final value is double, so usual arithmetic conversion applies and
compiler convert i and c into float and add them yielding a float result.
Storage Class
Every variable and function in C programming has two properties: type and
storage class. Type refers to the data type of variable whether it is character or
integer or floating-point value etc.
There are 4 types of storage class:
1
2
3
4
Automatic
External
Static
Register
A storage class defines the scope (visibility) and life time of variables and/or
functions within a C Program.
Scope of Variable (ACTIVE): What region of the program a variable is actually
available for use? [Range of availability]
Longevity (ALIVE): refers to the period during which a variable retains a given
value during execution of program.
Variables are also categorized, depending on the place of their declaration,
Internal (local); declared within the particular function,
External (global); declared outside of any function,
1. Automatic Variables
(Private/ Local/ Internal)
auto is the default storage class for all local variables. They are created
when the function is called and destroyed automatically when function
is exited.
int Count;
auto int Month;
The example above defines two variables with the same storage class.
auto can only be used within functions, i.e. local variables. The keyword
used for Automatic storage class is 'auto'. Keyword 'auto' are rarely
used.
#include<stdio.h>
#include<conio.h>
void main()
{
auto int a;
printf(%d,a)
}
auto int a;
or
int a;
Output:
1285
As seen above, the output is garbage value.
2. External Variables
(Public/ Global/ External)
Some applications it may be useful to have data which is accessible from
within any block and/or which remains in existence for the entire execution of
the program. Such variables are called global variables. The keyword used for
External storage class is 'extern'.
Default value of that variable is zero. Scope of that variable is global.
Variable is alive as long as the programs execution doesnt come to an end.
External variable can be declared outside all the functions or inside function
using 'extern' keyword.
Example 1
int a=10;
void main()
{
printf(%d,a);
}
int fun()
{
...
}
Output:
10
Local
variable
will
have
precedence over the global one.
Example 2
void main()
{
printf(%d,a);
}
int a=10;
int fun()
{
...
}
is
declared
after
Now it is possible
void main()
{
extern int a;
printf(%d,a);
}
int a=10;
int fun()
{
...
}
Output:
10
3. Static Variables
It persists until the end of program, and can be declared by keyword
static.
static int i;
It can be internal or external. If variable is static and internal than it is as
good as auto in case of its scope.
main()
{
int i;
auto int i;
static int i;
Static variable is initialized only once, when program is compiled, and never
again.
void fun()
{
static int x = 3;
}
4. Register Variables
If we want to keep variable in register rather than to store in memory
(RAM). By this faster execution.
register int x = 3;
Note: It is request by programmer, that means C will automatically
convert register variable into non-register variable.
Storage
Default
Scope
Lifetime
Till the
Local to the
control
block in
remain in
auto
Memory Garbage(unpredictable)
which it is the block in
which it is
declared
declared
Till the
Local to the
control
block in
remain in
Register Garbage(unpredictable)
which it is the block in
register
declared
which it is
declared
Local to the
Value
block in
persist in
static
Memory
ZERO [0]
which it is
between
declared
function call
Alive and
Active till
extern Memory
ZERO [0]
Global
the program
execution
does not
comes to
end