28
Functions

Functions

Embed Size (px)

DESCRIPTION

Functions in C Programming

Citation preview

Page 1: Functions

Functions

Page 2: Functions

Need for functions Need for the Functions

As, programs become more complex and large, several problems arise. Most common are

Algorithms for solving more complex problems become more difficult and ,hence difficult to design

Even if algorithms are known, its implementation becomes more difficult because the size of the program is longer

As programs become larger and complex, debugging and testing becomes more difficult.

As programs become larger and complex, more documentation is required to make the program understandable for people who will use and maintain the program

Page 3: Functions

FunctionsDefining a Function In C, a program is a collection of well defined and interrelated functions. The general form of a function is as follows

return-type function(type arg1, type arg2, …..){

local variables Declaration; executable statement 1;

executable statement 2; :

: return(expression); }

Page 4: Functions

FunctionsExample 1: Function for finding the biggest of

two integers

int find_big(int a, int b) {

if ( a > b) return a;else return b;

}

Page 5: Functions

FunctionsInvoking a Function

The user-defined functions are accessed from a function simply by its name and actual arguments / parameters enclosed with in parentheses.

These actual arguments are used to pass values formal arguments defined in the function.

When the function call is encountered, the control is transferred to the called function.

The formal arguments are copied by actual arguments and the execution of the function is carried out.

When the return statement is executed or last statement has finished its execution, the control is transferred back to the place of function call in the calling function.

Page 6: Functions

FunctionsExample Program for finding biggest of two integers using the function

void main( ) {

int num1, num2, big; scanf(“%d%d”, &num1, &num2); big=find_big(num1,num2); printf(“ The biggest is : %d “, big);

}int find_big(int a, int b) {

if ( a > b) return a; else return b; }

Page 7: Functions

Local and Global VariablesLocal and Global Variables

The variables declared inside a function are local to that function. It can be accessed only with in that function. Memories for the local variables are allocated only when the function is invoked and deallocated when the control returns to the calling function. These variables are also known to be automatic variables.

The variables declared outside of all function are global variables. These global variables are visible to all functions.

Page 8: Functions

Local and Global VariablesExample : Usage of Global Variables

int a; /* Global variable */float b; /* Global variable */void main(){ int c; /* Local variable*/ a=10; b=1.2; c= 20;

fun( ); printf(“ %d “, a); /* prints 20 */ }

void fun() {

a+=10;}

Page 9: Functions

Passing arguments to a functionPassing arguments to a Function

The mechanism used to pass data to a function is via argument list. There are two approaches to passing arguments to a function. These are

Call by Value

Call by Reference

Page 10: Functions

Call by ValueCall by Value

Example Program that illustrates Call by Value mechanism

void main() {

int a, b; a=10; b=20; swap(a, b); /* passing the values of a and b to c and d of swap function*/

printf(“%d %d”, a, b); /* Prints 10 20 */ }

void swap(int c, int d) /* Function used to swap the values of variables c and d */

{ int temp; temp = c; c = d; d = temp; }

Page 11: Functions

Call by ReferenceCall by Reference

In this approach, the addresses of actual arguments are used in the function call. The formal arguments should be declared as Pointer variables.

This approach is of practical importance while passing arrays and structures among functions and also for passing back more than one value to the calling function.

Page 12: Functions

Call by ReferenceExample : Program that illustrates Call by Reference mechanismvoid main() { int a, b; a=10; b=20; swap(&a, &b); /* passing the addresses of a and b to c

and d of swap function*/ printf(“%d %d”, a, b); /* Prints 20 10 */ } void swap(int *c, int *d) { int temp; temp = *c; *c = *d; *d = temp; }

Page 13: Functions

Function PrototypingFunction Prototyping Function prototype is a function declaration that specifies the return

type and data types of the arguments. A function prototype/declaration informing the compiler the number

and data types of arguments to be passed to the function, and the data type of the value returned by the called function.

Prototype for the function find_big int find_big(int, int);

Prototype for the swap function writtenvoid swap(int *, int*);

Usually prototypes appear at the beginning of a Program.

Page 14: Functions

RecursionRecursion

If a function is having a self-reference, it is recursion. In order that the function should not continue indefinitely, a recursive function must have the following properties:

- There must be certain criteria, called base criteria, for which a function does not call itself.

- Each time, when a function calls itself, it must be close to the base criteria. That is, it uses an argument(s) smaller than the one it was given at previous reference.

Page 15: Functions

RecursionExample Illustrative examples of Recursive functionFactorial Function : n! = n * (n-1)!

Base Criteria is 0! =1

int factorial( int n){ if(n = = 0) return 1;

else return( n* factorial(n-1));

}

Page 16: Functions

A function in C is a small “sub-program” that performs a particular task, and

supports the concept of modular programming design techniques. In

modular programming the various tasks that your overall program must

accomplish are assigned to individual functions and the main program

basically calls these functions in a certain order.

Review

Page 17: Functions

Don’t have to repeat the same block of code many times in your code. Make that code block a function and call it when needed.

– Function portability: useful functions can be used in a number of programs.

– Supports the top-down technique for devising a program algorithm. Make an outline and hierarchy of the steps needed to solve your problem and create a function for each step.

– Easy to debug. Get one function working well then move on to the others.

Reasons for functions

Page 18: Functions

Easy to modify and expand. Just add more functions to extend program capability

– For a large programming project, you will code only a small fraction of the program.

– Make program self-documenting and readable.

Reasons for functions

Page 19: Functions

In order to use functions, the programmer must do three things

– Define the function – Declare the function – Use the function in the main code.

Page 20: Functions

The function definition is the C code that implements what the function does.

Function definitions have the following syntax

return_type function_name (data type variable name list)

{ local declarations; function statements;}

Page 21: Functions

A function returns a value to the calling program with the use of the keyword

return, followed by a data variable or constant value.

The return statement can even contain an expression. Some examples

return 3; return n; return ++a; return (a*b);

Page 22: Functions

When a return is encountered the following events occur:

1 execution of the function is terminated and control is passed back to the calling program, and

2 the function call evaluates to the value of the return expression.

Page 23: Functions

If there is no return statement control is passed back when the closing brace of the function is encountered (“falling off the end”).

Page 24: Functions

The data type of the return expression must match that of the declared return_type for the function.

float add_numbers (float n1, float n2) { return n1 + n2; /*legal*/ return 6; /*illegal, not the same data

type*/ return 6.0; /*legal*/ }

Page 25: Functions

It is possible for a function to have multiple return statements. For example:

double absolute(double x) { if (x>=0.0) return x; else return -x;

Page 26: Functions

The number of arguments in the function call must match the number of

arguments in the function definition. – The type of the arguments in the

function call must match the type of the arguments in the function definition. – The actual arguments in the function

call are matched up in-order with the dummy arguments in the function

definition.

Considerations when using Functions

Page 27: Functions

– The actual arguments are passed by-value to the function. The dummy

arguments in the function are initialized with the present values of the actual

arguments. Any changes made to the dummy argument in the function will NOT

affect the actual argument in the main program

Considerations when using Functions

Page 28: Functions

Function prototypes are used to declare a function so that it can be used in a program before the function is actually defined.