A function in C is a block of code (program statements) that has a name and has a reusable property i.e. it can be executed from as many different points in a C Program as required. We can formally define a function as:
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, named block of statements that perform a coherent task of same kind.
(sources: Isaac Computer Science, Jim, John Bell)
The name of the function is unique in a C Program and is Global. It means that a function can be accessed from any location with in a C Program. We pass information to the function called arguments 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.
Table of Contents
- Structure of a Function
- Functions in C++ Programming
- Why we use Functions?
- Types of functions
- Passing Arguments to function
- Returning Values from Functions
- Call by Value
- Call by Reference
Structure of a Function
There are two main parts of the function. The function header and the function body.
1 2 3 4 5 6 | int sum(int x, int y) { int ans = 0; //holds the answer that will be returned ans = x + y; //calculate the sum return ans //return the answer } |
Function Header
In the first line of the above code
1 | int sum(int x, int y) |
It has three main parts
- The name of the function i.e. sum
- The parameters of the function enclosed in parenthesis
- Return value type i.e. int
Function Body
The function body is contained within curly braces {}
and follows the function header. The function body may contain any combination of statements, control structures, variables, and other expressions, and may optionally return a value using the return
statement.
Function Prototype
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
1 | 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++ Programming
Functions in C++ 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.
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | #include <stdio.h> using namespace std; void starline( ); int 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; } // function defintion void starline () { for(int j=0; j<45; j++){ cout << "*" ; } cout << endl; } |
The output from the program looks like this:
1 2 3 4 5 6 7 8 | ************************************* 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 function’s 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
- 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.
- 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 can’t use a variable without first telling the compiler what it is, you also can’t use a functions without telling the compiler about it, There are two ways to do this . The approach we show here is to declare the function before it is called. The other approach is to define it before it’s called. ; we’ll examine that next.) in the Table program, the functions starline() is declared in the line.
1 | 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 function 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 it’s 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:
1 | 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. Here’s the definition for starline( ) .
1 2 3 4 5 6 | void starline ( ) { for ( int j=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 decelerator. 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.
Types of functions
There are basically two types of functions i.e. library function and user defined function.
- Library function is a pre-written that is included in a library of the compiler such as printf( ), scanf( ) etc.
- User defined function is a function that user writes to perform certain tasks such as we are discussing in this article.
Note the following points about functions
- C program is a collection of one or more functions
- A function gets called when the function name is followed by a semicolon for e.g.
1 | main (){ message (); } |
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.
1 2 3 4 5 6 | message ( ){ statement 1; statement 2; statement 3; } |
Any function can be called from any other function even main( ) can be called from other functions. for e.g.
1 2 3 4 5 6 7 8 9 | main (){ message ( ); } message () { printf ("\n Hello"); main (); } |
A function can be called any number of times for e.g.
1 2 3 4 5 6 7 8 9 | main (){ message(); message(); } message() { printf ("\n Hello"); } |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | main(){ message1 (); message2 (); } message2 () { printf ("\n I am learning C"); } message1 () { printf ("\n Hello "); } |
A function can call itself such a process as called “recursion” in computer programming.
A function can be called from other function, but a function cannot be defined in an-other function. The the following program code is incorrect, since we defined function argentina() inside another function.
1 2 3 4 5 6 7 | main (){ printf ("\n I am in main"); argentina () { printf {"\n I am in argentina"); } } |
Any C program contains at least one function.
If a program contains only one function, it must be main( ).
In a C program if there are more than one functional present then one of these functional must be main( ) because program execution always begins with main( ).
There is no limit on the number of functions that might be present in a C program.
Each function in a program is called in the sequence specified by the function calls in main( )
After each function has done its thing, control returns to the main( ), when main( ) runs out of function calls, the program ends.
Passing Arguments to function
An argument is a piece of data (an into value, for example) 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 to a function
As an example, let’s suppose we decide that the starline( ) function in the last example 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
Here is a program, tablearg.cpp, that incorporates just such a function. We use arguments to pass the character to be printed and the number of times to print it .
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | #include <iostream> using namespace std; void repchar(char, int); //function declaration int 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; } // funtion definiton void repchar ( char ch , int n ) { //function body for (int j=0; j<n; j++) { cout << ch; } cout << endl; } |
The new function is called repchar ( ), Its declaration looks like this
1 | 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:
1 | 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( ).
1 | repchar ("=" , 23); |
Tells it to print a line of 23 equal signs. The third call again prints 43 dashes. Heres the output form tablearg.cpp.
1 2 3 4 5 6 7 8 | ------------------------------------------- Data type Range ======================= char -128 to 128 short -32,768 to 32,767 int system dependent double -2, 147,483,648 to 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
1 2 3 | 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 to a function
In the tablearg.cpp 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, incorporates the same repchar() function as did tablearg.cpp, but let the user specify the character and the number of times it should be repeated.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | //demonstrates variable arguments #include <iostream> using namespace std; void repchar(char,int); int main() { char chin; int nin; cout << "enter a character:"; cin >> chin; cout << "enter a number of times to repeat it:"; cin >> nin; repchar (chin, nin); return 0; } //function definition void repchar(char ch, int n) { for(int j=0; j<n; j++){ cout << ch; } cout << endl; } |
1 |
Here is some sample interaction with var arg
1 2 3 | Enter a character:+ Enter number of times to repeat it:20 ++++++++++++++++ |
Here chin and nin in main() are used as arguments to repchar():
1 | 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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | //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 <<endl; return 0; } 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
1 | 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 ;
1 | 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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | #include <stdio.h> void swapy (int, int); int main () { int a = 10, b=20; swapy (a,b); printf ("\na = %d b = %d", a,b); return 0; } void 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.
To pass a value by reference, argument pointers are passed to the functions just like any other value.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | #include <stdio.h> void swapr(int * x, int * y) { int t; t = *x; *x = *y; *y = t; } int main () { int a = 10, b =20; swapr (&a, &b); printf ("\n a = %d b= %d", a, b); return 0; } |
The output of the above program would be a = 20 b =10
Here are some of the C Programs that use functions. You can study the programs to further understand the concept of functions and how to use them in your programs.