Sei sulla pagina 1di 15

What is a Function?

A function is a block of code that has a name and it has a property that it is reusable i.e. it can be executed from as many different points in a C Program as required. Function groups a number of program statements into a unit and gives it a name. This unit can be invoked from other parts of a program. A computer program cannot handle all the tasks by it self. Instead its requests other program like entities called functions in C to get its tasks done. A function is a self contained block of statements that perform a coherent task of same kind The name of the function is unique in a C Program and is Global. It neams that a function can be accessed from any location with in a C Program. We pass information to the function calledarguments specified when the function is called. And the function either returns some value to the point it was called from or returns nothing. We can divide a long C program into small blocks which can perform a certain task. A function is a self contained block of statements that perform a coherent task of same kind.

Structure of a Function
There are two main parts of the function. The function header and the function body.
int sum(int x, int y) { int ans = 0; ans = x + y; return ans } //holds the answer that will be returned //calculate the sum //return the answer

Function Header
In the first line of the above code
int sum(int x, int y)

It has three main parts

1. The name of the function i.e. sum 2. The parameters of the function enclosed in paranthesis 3. Return value type i.e. int

Function Body
What ever is written with in { } in the above example is the body of the function.

Function Prototypes
The prototype of a function provides the basic information about a function which tells the compiler that the function is used correctly or not. It contains the same information as the function header contains. The prototype of the function in the above example would be like
int sum (int x, int y);

The only difference between the header and the prototype is the semicolon ; there must the a semicolon at the end of the prototype

Functions in C/C++ Programming


Functions groups a number of program statements into a unit and gives it a name. This unit can be invoked from other parts of a program. A computer program cannot handle all the tasks by it self. Instead its requests other program like entities called functions in C to get its tasks done. A function is a self contained block of statements that perform a coherent task of same kind. e.g

Simple Functions
Our first example demonstrates a simple function those purpose is to print a line of 45 asterisks.The example program generates a table , and lines of asterisks are used to make the table more readable. Heres the listing for Table:
// table .cpp // demonstrates simpole function # include using namespace std;

void starline( ); into main () { starline ( ); cout << "Data type Range" << endl; starline ( ); cout << "char -128 to 127 " << endl << "short -32 ,768 to 32,767"<< endl << "int system independent: << endl << " long q-2,147,483,648 to 2,147,483,647" << endl; starline ( ); return 0; } //"""""""""""""""""""""""".. //starline ( ) // function defintion void starline ( ) { for(into j=0;j<45; j++) cout << "*" ; cout << endl; } The output from the program looks like this ************************************* Data type Range ************************************* Char -128 to 127 Short -32,768 to 32,767 Into system dependent Double -2,147,483,648 to 2,147,483,647 *************************************

Why we use Functions


The most important reason to use functions is to aid in the conceptual organization of a program. Another reason to use functions is to reduce program size. Any sequence of instructions that appears in program more than once is a candidate for being made into a function. The functions code is stored in only one place

in memory, even though the function is executed many times in the course of the program.

Two reasons
1. Writing functions avoids rewriting the same code over and over. Suppose that there is a section of code in a program that calculates area of a triangle. If, later in the program we want to calculate the area of a different triangle we wont like to write the same instructions all over again. Instead we would prefer to jump to a section of code that calculates area and then jump back to the place from where you left off. This section of code is nothing but a function. 2. Using functions it becomes easier to write programs and keep track of what they are doing. If the operation of a program can be divided in to separate activities, and each activity placed in a different function, then each could be written and checked more or less independently. Separating the code in to modular functions also makes the pro-gram easier to design and understand.

Function Declaration
Just as you cant use a variable without first telling the compler what it is, you also cant use a funciotns without teling the compiler about it, There are two ways to do this . The approach we show here ist o declare the funtion before it is called. The other approach is to define it before its called. ; well examine that next.) in the Table program, the functions starline() is declared in the line.
Void starline ( );

The declaration tells the compiler that at some later point we plan to present a function called starline. The keyword void specifies that the function has no return value, and the empty parentheses indicate that it takes no arguments. Notice that the funtois declarations is terminated with a semicolon It is a complete statement in itself. Function declarations are also called prototypes, since they provide a model or blueprint for the function. They tell the compiler, a function that looks like this is coming up later in the program, so its all right if you see references to it before you see the function itself.

Calling the Function


The function is called (or invoked) three times from main (). Each of the three calls look like this:
Starline():

This is all we need to call a function name,followed by parentheses. The syntax of the call is very similar to that of declaration, except that the return type is not used. A semicolon terminates the call. Executing the call statement causes the function to execute; that is, control is transferred to the function, the statement in the function definition are executed, and then control returns to the statement following the function call.

Function Definition
Finally, we come to the functions its self, which is referred to as the functions definition, The definition contains the actual code for the function. Heres the definition for starline( ) .
void starline ( ) { for ( intj=0, j < 45; j++ ) cout << "*" ; cout << endl; }

The definition consists of a line called the decelerator, followed by the function body , The function body is composed of the statements that make up the function, delimited by braces. The decelerator must agree with the declaration: It must use the same function name, have the same argument types in the same order( if there are arguments), and have the same return type. Notice that a semicolon does not terminate the declarator. Figure shows the syntax of the function declaration, function call, and function definition. When the function is called, control is transferred to the first statement in the functions body. The other statements in the function body are then

executed, and when the closing brace is encountered, control returns to the calling program.

There are basically two types of functions


1. Library functions Ex. printf ( ), scanf ( ) etc. 2. User defined function e.g the function message mentioned above. The following point must be noted about functions (i) C program is a collection of one or more functions (ii) A function gets called when the function name is followed by a semicolon for e.g. main ( ) { message ( ); } 3. Function is defined when function name is followed by a pair of braces in which one or more statements may be present for e.g. message ( ) { statement 1; statement2; statement 3; } 4. Any function can be called from any other function even main ( ) can be called from other functions. for e.g. main ( ) { message ( ); } message ( )

{ printf ( \n Hello); main ( ); } 5. A function can be called any number of times for eg. main () { message ( ); message ( ); } message ( ) { printf (\n Hello); } 6. The order in which the functions are defined in a program and the order in which they get called need not necessarily be same for e.g. main ( ); { message 1 ( ); message 2 ( ); } message 2 ( ) { printf (\n I am learning C); }

message 1 ( ) { printf ( \n Hello ); } 7. A function can call itself such a process as called recursion. 8. A function can be called from other function, but a function cannot be defined in an-other function. These the following program code would be wrong, since Argentina is being defined inside another function main ( ). main ( ) { printf (\n I am in main); argentina ( ) { printf {\n I am in argentina); } } 9. Any C program contains at least one function. 10. If a program contains only one function, it must be main( ). 11. In a C program if there are more than one functional present then one of these func-tional must be main( ) because program execution always begins with main( ). 12. There is no limit on the number of functions that might be present in a C program. 13. Each function in a program is called in the sequence specified by the function calls in main( ) 14. After each function has done its thing, control returns to the main( ), when main( ) runs out of function calls, the program ends. Functions declaration and prototypes Any function by default returns an int value. If we desire that a function should return a value other than an

int, then it is necessary to explicitly mention so in the calling functions as well as in the called function. for e.g
main ( ) { float a,b, printf ("\n Enter any number"); scanf ("\% f", &a ); b = square (a) printf ("\n square of % f is % f", a,b); } square (float X) { float y; Y = x * x; return (y); }

the sample run of this program is Enter any number 2.5 square of 2.5 is 6.000000 Here 6 is not a square of 2.5 this happened because any C function, by default, always returns an integer value. The following program segment illustrates how to make square ( ) capable of returning a float value.
main ( ) { float square ( ); float a, b; printf ("\n Enter any number "); scanf ("%f" &a); b = square (a); printf ("\n square of % f is % f, " a, b); } float square (float x) { float y; y= x *x; return ( y); }

sample run Enter any number 2.5 square of 2.5 is 6.2500000

PASSING ARGUMENTS TO FUNCTION


An argument is a piece of data (an into value, for exp) passed from a program to the function. Arguments allow a function to operate with different values, or even to do different things, depending on the requirements of the program calling it.

PASSING CONSTANTS
As an exp, lets suppose we decide that the starline ( ) function in the last exp is too rigid. Instead of a function that always prints 45 asterisks, we want a function that will print any character any number of times Heres a program, TABLEARG, that incorporates just such a function. We use arguments to pass the character to be printed and the number of times to print it .
// tablearg. Cpp // demonstrates funciotn arguments # include < iostream> using namespace std; void repchar(char, int); //function declaration in main ( ) { repchar(" " " , 43); cout << " Data type Range" <, endl; repchar ( "=", 23); //call to function cout << " char -128 to 128" < endl << "short -32,768 to 32,767" < endl << " int system dependent " << endl << " double -2, 147,483,648 to 2,147,483,647" << endl; repchar("-" , 43); return 0; }//""""""""""""""""""""""""""". //repchar ( ) // funtion definiton void repchar ( char ch , int n ) { for ( into j=0; j<n; j++) //function body

cout < ch; cout << endl; }

The new function is called repchar ( ), Its declaration looks like this Void repchar ( char, int); // declaration specifies data types The items in the parentheses are the data types of the argument that will be sent to repchar( ): char and int. In a function call, specific values constants in this case are inserted in the appropriate place in the parentheses: Repchar(-, 43); // function call specifies actual values This statement instructs repchar ( ) to print a line of 43 dashes. The values supplied in the call must be of the types specified in the declaration: the first argument, the - character , must be of type[ char; and the second arguments, the number 43 must be of type int. The types in the definition must also agree. The next call to repchar ( ). Repchar (= , 23); Tells it to print a line of 23 equal signs. The third call again prints 43 dashes. Heres the output form TABLEARG. """""""""""""" data type Range =============== char -128 to 127 short -32,768 to 32,767 int system dependant long -2,147,483,648to 2,147,483,647

The calling program supplies arguments such as - and 43 ,to the function. The variables used within the functions to hold the argument values are called parameters; in repchar() the are ch and n.These decelerator names ch and n, are used in the functions as they were normal variables. Placing them in the decelerators is equivalent to defining them with the statements like Char ch; Int n;l When the function is called, its parameters are automatically initialized to the values passed by the calling program.

PASSING VARIABLES
In the tablearg example the arguments were constants - 43,and so on. Lets look at an example where variables, instead of constants ,are passed as arguments. This program,VARARG,incorporates the same repchar()function as did tablearg,but let the user specify the character and the number of times it should be repeated.
//vararg.cpp //demonstrates variable arguments # include <iostream> using namespace std; void repchar(char,int); int main() { char chin; int nin; cout<<"enter a character:"; cin>>nin; cout<<"enter a number of times to repeat it:"; cin>>nin; repchar (chin,nin); return 0; } //"""""""""""""""""""""""""""

//repchar () //function definition void repchar(char ch,int n) { for(int j=0,j<n;j++) cout<<ch; cout<<end1; }

Here is some sample interaction with vararg Enter a character:+ Enter number of times to repeat it:20 ++++++++++++++++ Here chin nd nin in main ()are used as arguments to repchar(): rephar()(chin,nin); // function call The data types of variables used as arguments must match those specified in the function declaration and definition, just as they must for constant. That is chin must be a char and nin must be an int.

RETURNING VALUES FROM FUNCTIONS


When a function completes its execution, it can return a single value to the calling program. Usually this return value consists of an answer to the problem the function has solved. The next example demonstrates a function that returns a weight in kg after being given a weight in ponds.
//convert.cpp //demonstrates return values, converts a pound to kg #include <iostream> using namespace std; float lbstokg(float); int main() { float lbs,kgs; cout<<"enter your weight in pounds:";

cin>>lbs; kgs=lbstokg(lbs); cout<<"your weight in kg is "<<kgs<<end1; return 0; } //""""""""""""""""".. //lbstokg() //converts pounds to kg float lbstokg(float pounds) { float kg=0.453592*pounds; return kg; }

When a function returns a value. The data type of this value must be specified. The function declaration does this by placing the data types, float in this case, before the function name in the declaration and the definition. Functions in earlier program examples returned no value, so the return type was void. In the above function lbstokg() returns type float, so the declaration is
Float lbstokg(float);

The first float specifies the return type. The float in parentheses s specifies that an argument to be passed to lbstokg() is also of type float.

CALL BY VALUE
In the preceding examples we have seen that whenever we called a function we have always passed the values of variables to the called function. Such function calls are called calls by value by this what it meant is that on calling a function we are passing values of variables to it. The example of call by value are shown below ;
sum = calsum (a, b, c); f = factr (a);

In this method the value of each of the actual arguments in the calling function is copied into corresponding formal arguments of the called function. With this method the changes made to the formal arguments in the called function have no effect on the values of actual argument in the calling function. The following program illustrates this:

main ( ) { int a = 10, b=20; swapy (a,b); printf ("\na = % d b = % d", a,b); } swapy (int x, int y) { int t; t = x; x = y; y = t; printf ( "\n x = % d y = % d" , x, y); }

The output of the above program would be; x = 20 y = 10 a =10 b =20

CALL BY REFERENCE
In the second method the addresses of actual arguments in the calling function are copied in to formal arguments of the called function. This means that using these addresses we would have an access to the actual arguments and hence we would be able to manipulate them the following program illustrates this.
main ( ) { int a = 10, b =20, swapv (&a, &b); printf ("\n a = %d b= %d", a, b); } swapr (int **, int * y) { int t; t = *x *x = *y; *y = t; }

The output of the above program would be a = 20 b =10.

Potrebbero piacerti anche