0% found this document useful (0 votes)
122 views

Chapter 12

Functions are used to encapsulate operations and return information. Declaring functions involves specifying the return type and parameters. Defining functions involves writing the function body. Functions can be called by passing arguments. There are four categories of functions based on whether they accept arguments and return values. Functions allow code reuse and modularity. Arrays can be passed to functions, which receive the array address rather than a copy. Functions can call other functions, and can call themselves recursively. Variables inside functions have automatic storage duration and local scope.

Uploaded by

alysonmicheaala
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
122 views

Chapter 12

Functions are used to encapsulate operations and return information. Declaring functions involves specifying the return type and parameters. Defining functions involves writing the function body. Functions can be called by passing arguments. There are four categories of functions based on whether they accept arguments and return values. Functions allow code reuse and modularity. Arrays can be passed to functions, which receive the array address rather than a copy. Functions can call other functions, and can call themselves recursively. Variables inside functions have automatic storage duration and local scope.

Uploaded by

alysonmicheaala
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 12

Functions

12. FUNCTIONS
Objectives
Declaring and Defining Functions Returning Multiple Values From Functions Passing Arrays to Functions Storage classes

This chapter covers functions. Functions are used to encapsulate a set of operations and return information to the main program or calling routine. Encapsulation is detail, information or data hiding. Once a function is written, we need only be concerned with what the function does. That is, what data it requires and what outputs it produces. The details, "how" the function works, need not be known. The use of functions provides several benefits. First, it makes programs significantly easier to understand and maintain. The main program can consist of a series of function calls rather than countless lines of code. A second benefit is that well written functions may be reused in multiple programs. The C standard library is an example of the reuse of functions. A third benefit of using functions is that different programmers working on one large project can divide the workload by writing different functions. 6.1 Declaring & Defining Functions Function definition The function definition consists of the prototype and a function body, which is a block of code enclosed in parenthesis. A declaration or prototype is a way of telling the compiler the data types of the any return value and of any parameters, so it can perform error checking. The definition creates the actual function in memory. The general format of a function definition is: return_type function_name(list of parameters) { local variable declaration; function_body; } The return_type is nothing but the return type of a function. By default, all C functions having the return type as int including main. The parameters also called as arguments. Function declaration A function is declared with a prototype. The function prototype, consists of the return type, a function name and a parameter list. The function prototype is also called the function declaration. The format of function declaration is: return-type function_name(parameter list); Here are some examples of prototypes. int max(int n1, int n2); /* A programmer-defined function */ int printf(const char *format,...); /* From the standard library */

Functions A function should always be declared prior to its use to allow the compiler to perform type checking on the arguments used in its call. Depending on the compiler and compiler options used, it is possible to not declare functions prior to use but then error checking on the arguments in the function call will not be performed. Function call A function can be called by simply using the function name followed by a list of actual parameters (or arguments). The general format of a function call is: function_name(list of parameter); for example, divide(10,5); divide(m,n); Category of functions Functions are categorized into 4 types: 1. Function without any arguments and function without any return value. 2. Function with arguments and function without any return value. 3. Function without any arguments but functions with return value. 4. Function with arguments and function with return value. void functions When a function does not take any parameters and does not return anu value, its prototype is written as: void function-name(void); for example, void display(void); Function without any arguments and function without any return value When a function has no arguments, it does not receive any data from the calling function. Program: void printline(void); void main() { printline(); } void printline(void) { int i; /* local variable i */ for(i=0;i<30;i++) printf(%c,*); } Output: *****************************

Functions Observe that variables can be declared within a function. These variables are local variables. They have local scope. Scope refers to the section of code where a variable name is valid and may be used. Function with arguments and function without any return value We can pass the values to a function by 2 ways. They are: Call by value Call by reference Program: int factorial(int n); void main() { int n; printf(Enter the number of factorial \n); scanf(%d,&n); factorial(n); } int factorial(int n) { int j,f=1; for(j=0;j<n;j++) f=f*j; printf(\n The factorial of %d numbers is:%d,n,f); } Output: Enter the number of factorial 5 The factorial of 5 numbers is:120 In the function call factorial(n), n is called an actual argument, which become the value of the formal arguments inside the called function. The actual and formal arguments should match in number, type and order. The values of actual arguments are assigned to the formal arguments on a one to one basis, starting with the first argument. This method is called call by value or pass by value method. When a function call is made, only a copy of the values of actual arguments is passed into the called function. Function without any arguments but functions with return value The return statement can be used to return a single value from a function. The return statement is optional. For instance, the function printline does not return a value. Techniques for returning multiple values from a function will be covered later in the lesson. The general format of the return statement is:

Functions return(value); will return the value. or return(expression); will return the value of an expression. For example, return(c); This return statement returns the value of the varible c. return(a*b); This return statement returns the value of expression a*b; Program: #include <stdio.h> #define PI 3.14 float area(); void main() { float a; a=area(); printf(\n The area of the circle is: %f,a); } float area() { float radius; printf(\n Enter the radius of the circle:); scanf(%f,&radius); return(PI*radius*radius); } Output: Enter the radius of the circle:4.5 The area of the circle is:63.585 Function with arguments and function with return value The function receives data from the calling function through arguments and as well as send back the data to the calling function. Program: int FindMax(int,int); void main() { int a,b; printf(Enter the values of a and b \n); scanf(%d%D,&a,&b); printf(\n The maximum is=%d,FindMax(a,b)); } int FindMax(int n1, int n2) { if (n1 > n2)

Functions { return n1; } else { return n2; } } Output: Enter the values of a and b 45 81 The maximum is=81 Nesting of functions If a function calls another function then it is called nesting of function. Program: float ratio(int x, int y, int z); int differ(int x,int y); main() { int a,b,c; scanf(%d%d%d,&a,&b,&c); printf(%f \n,ratio(a,b,c)); } float ratio(int x,int y,int z) { if (differ(y,z)) return(x/(y-z)); else return(0.0); } int differ(int p,int q) { if (p!=q) return(1); else return(0); } Recursion When a function calls itself is called recursion. For example, main() { fun(); }

Functions void fun() { printf(Example for recursion); fun(); } 6.3 Passing arrays to functions Like the values of simple variables, it is also possible to pass the values of an array to a function. When an array is passed into a function, the function receives not a copy the array, but instead the address of the first element of the array. The function receives a pointer to the start of the array. Any modifications made via this pointer will be seen in the calling program. For example, the call largest(a,n); will pass the whole array a to the called function. Let's see how this works. Suppose the main program has an array of 10 integers and that a function has been written to double each of these. void doubleThem(int a[], int size); int main() { int myInts[10] = {1,2,3,4,5,6,7,8,9,10}; doubleThem(myInts, 10); return 0; } void doubleThem(int a[], int size) { int i; for (i = 0; i < size; i++) { a[i] = 2 * a[i]; } for (i = 0; i < size; i++) { printf(%d,a[i]); } } Call by reference In this method the arguments are passed by reference. That is we pass the addresses of locations where the values of arguments are stored in the memory. Using pointers we can do this. Rules for pass by pointers The types of the actual and formal arguments must be same. The formal arguments in the function header must be prefixed by the indirection operator *.

Functions In the prototype, the arguments must be prefixed by the symbol *. Program: int swap(int *p1,int *p2); void main() { int m,n; printf(Enter values \n); scanf(%d%d,&m,&n); printf(The values of m and n before swapping\n); printf(%d%d,m,n); swap(&m,&n); printf(The values of m and n after swapping\n); printf(%d%d,m,n); } int swap(int *p1,int *p2) { int temp; temp=*p1; *p1=*p2; *p2=temp; } Output: Enter values 56 21 The values of m and n before swapping 56 21 The values of m and n after swapping 21 56 6.4 Storage Classes Types of storage classes Automatic storage class External storage class Static storage class Register storage class Automatic The scope of a variable is simply the part of the program where it may be accessed or written. It is the part of the program where the variable's name may be used. If a variable is declared within a function, it is local to that function. These are also called as local variables. Variables of the same name may be declared and used within other functions without any conflicts. For instance, int fun1() { int a; int b; ....

Functions } int fun2() { int a; int c; .... } Here, the local variable "a" in fun1 is distinct from the local variable "a" in fun2. Changes made to "a" in one function have no effect on the "a" in the other function. Also, note that "b" exists and can be used only in fun1. "C" exists and can be used only in fun2. The scope of b is fun1. The scope of c is fun2. Note that main is also a function. Variables declared after the opening bracket of main will have all of main as their scope. int fun1(); int fun2(); int main() { int a; int b; int x,y,z; x = fun1(); y = fun2(); return 0; } int fun1() { int a; int b; .... } int fun2() { int a; int c; } So here, a, b, x, y and z are local to main, a and b are local to fun1 and a and c are local to fun2. Notice that in this example there are three distinct local variables all named "a". Local variables are also referred to as automatic variables. They come to life at the beginning of a function and die at the end automatically. External Variables Variables may also be defined outside of any function. These are referred to as global or external variables. The scope of an external variable is from its declaration to the end of the file. Global variables are initialized to zero. For instance:

Functions Program: void fun1(); void fun2(); void fun3(); int x; int main() { printf(\n x value is:%d,x); printf(\n x value is:%d,fun1()); printf(\n x value is:%dfun2()); printf(\n x value is:%d,fun3()); return 0; } void fun1() { x=x+5; return(x); } void fun2() { int x=3; return(x); } void fun3() { x=x+7; return(x); } Output: 0 5 3 12 If the local variable and global variable has the same name then the local hides the visibility of global. Here, global variable x is initialized to 0. In main, x has the value 0. In fun1, x has the value 5, because x is incremented by 5. In fun2, x is the local variable. This hides the value of global x. so, in fun2, x has the local value 3. In fun3, x is global. The global value of x(5) is incremented by 7. so the value is 12. int j; ... int main() { .... }

Functions

int k; float funA() { } int l; float funB() { } The variable "j" will be visible in main, funA and funB. The variable "k" will be visible in funA and funB only. The variable "l" will be visible only in function funB. An important distinction between automatic (local) variables and external (global) variables is how they are initialized. External variables are initialized to zero. Automatic variables are undefined. They will have whatever random value happens to be at their memory location. Automatic, or local, variables must always be initialized before use. It is a serious error, a bug, to use a local variable without initialization. The scope for a function is similar to that of an external variable. Its scope is from the functions declaration to the end of the file. int fun1(); int fun2(); int main() { .... } int fun3(); int fun1() { int i; .... i = fun3(); .... } int fun2() { ..... } int fun3() { ..... } Notice that here fun1 and fun2 may be called from main but fun3 may not. The function fun3 can be called from fun1 and fun2 or from anywhere after its declaration.

Functions Static Variables The keyword "static" has two different uses, depending on whether it is applied to an external variable or function or to an automatic variable. When applied to an external variable (global) variable the scope of that variable to the file in which it is declared. This is useful to hide buffers and variables that are used only by functions in a particular file. Likewise, when used with a function, the scope of that function is limited to the file in which it is defined. For instance, if several input related routines in a file required a buffer to store data, then static char inputbuff[10000]; would declare a buffer that had its scope limited to that file. When used with an automatic variable (local variable), the keyword static gives persistence to the variable. This is particularly useful to maintain information in a function between calls. All non-static automatic variables in a function are created when it is called and destroyed when it exists. Static variables will maintain their values between calls. This is useful if the function needs to do special initializations on its first call. int example() { static int first = 1; if (first) { first = 0; /* This code is executed only with the first call */ /* Perform initializations, initialize hardware, etc. */ } /* Rest of the function will be executed every time */ .... .... } For example, consider the following program. int stat(int); void main() { int i; for(i=1;i<=3;i++) stat(); } int stat() { static int x=3; printf(%d,x++); } Output: 3 4 5

Functions

Register variables Register variables are used to register count; Summary It is a syntax error if the types in the declaration and definition do not match. The function prototype must be terminated by semicolon. Functions return integer value by default. If a function does not return any value, the return type must be declared void. A return statement is required if the return type is anything other than void. Defining a function within the body of another function is not allowed. A function without return statement cannot return a value, when the parameters passed by value. A return statement can occur anywhere within the body of a function. A function can have more than one return statement. If a function has no parameters, the parameter list may be declared void. A function definition may be placed either after or before the main function.

Review Questions State whether true or false 1. C functions can return only one value at a time. 2. A function can be defined within the main function. 3. Any name can be used as a function name. 4. A function can call itself. 5. The return type of a C function is float by default. 6. Global variables are initialized to 0 automatically. Fill in the blanks 1. The parameters used in a function call are called ___________. 2. A variable declared inside a function is called __________. 3. A __________ aids the compiler to check the matching between the actual arguments and the formal ones. 4. In prototype declaration, specifying __________ is optional. 5. A function that calls itself is known as a __________. Programming Exercises 1. Write a program to find the largest number in an array using functions. 2. Write a function to perform the arithmetic operations between two numbers. 3. Write a function to find the minimum of two numbers. 4. Write a program to subtract two matrices using functions.

You might also like