What are the Functions?
A function is a self-contained block or a sub-program of one or more statements that perform a special task (specific and well-defined tasks) when called. A function is a block of statement that performs some kind of task. Every C program can be thought of as a collection of these functions.
Why Use functions?
- Writing functions avoids rewriting the same code over and over.
- By using functions it becomes easier to write programs and keep track of what they or doing.
- Using functions large programs can be reduced to smaller ones. It is easy to debug and find out the errors in it. It also increases readability.
Points to remember?
- Purpose of function is code reuse.
- We can define the function randomly.
- From any function, we can call any other function.
- Compilation process always starts from the top to bottom.
- Execution process will start from the main and end with main.
- Calling a function which is defined later, and then need to declare it (for archiving the compilation errors).
- Function declaration means need to mansion return type, name of the function and taking type.
- In function defining the first line is called function decelerator.
- The function declaration must match with function decelerator.
Advantages of Functions
When programs are very lengthy, handling those programs become difficult. It is also difficult to debug and understand such lengthy programs. In order to overcome these drawbacks, complex programs can be subdivided into smaller modules. These modules are implemented using functions. Hence these subprograms or functions are easy to understand, debug and test.
The part of the program which has to be repeated many times can be written as a function and can be called wherever needed to avoid repetition. This helps in reducing the size of the program.
- A function can be shared by many programs.
- It facilitates top-down modular programming.
How does function work?
Once a function is defined and called, it takes some data from the calling function and returns a value to the called function.
The detail of the inner working of a function is unknown to the rest of the program. Whenever a function is called, control passes to the called function and working of the calling functions are stopped. When the execution of the called function is completed, control returns back to the calling function and execute the next statement.
The values of the actual arguments passed by the calling function are received by the formal arguments of the called function. The number of actual and formal arguments should be the same. Extra arguments are discarded if they are defined. If the formal arguments are more than the actual arguments then the extra arguments appear as garbage. Any mismatch in the data type will produce an unexpected result.
The function operates on formal arguments and sends back the result to the calling function. The return() statement performs this task.
Structure of a function
void message(); /* function prototype declaration */ void main() { function_name(parameter list1); /* function calling */ //Ex: message( a,b,c); } /* function definition */ Return_value_type function_name(parameter_list2) //Ex: int message (x,y,z) { Local variable Declarations .... Statements return (expression); }
- Return_value_type it is the type that the function returns, according to the value.
- Function_name every function is known by a particular name.
- Parameter_list: parameters are also known as arguments. This list that is enclosed within the parenthesis can have variables that are separated by a comma. These arguments have communication between the calling function and the called function.
- The arguments of calling functions are actual arguments (parameter_list1).
- The arguments of the called function are formal arguments (parameter_list2).
- Valiable declarations: Local/global variables are declared.
- Statements: these refer to different statements such as the printf(), scanf() statements of other assignment statements.
- Return (expression): returns the value of an expression to the calling function.
- Function call: a compiler executes the function when a semi-colon (;) is followed by the function name. a function can be called simply using its name like another C statement, terminated by a semicolon (;).
Parameters in functions
Depending on the location of parameters in functions, they are categorized as actual parameters and formal parameters.
- Actual parameters: The parameters that are passed in a function call are called actual parameters. These parameters are defined in the calling function. Actual parameters can be variables, constants or expressions.
- Formal parameters: The parameters that are used in the function definition are called formal parameters. These parameters belong to the called function. These can be only variables but not expression or constants.
Function Prototyping
A prototype statement helps the compiler to check the return type and argument type of the function. The prototypes of built-in functions are given in the respective header files. Those we include using #include directive. while defining user-defined functions it is a must to declare its prototype.
A function prototype is a declaration of a subroutine (or a function) that specify the function name, an argument list with data types and the return type of a function without the function body. A function prototype specifies the function name, the argument list and return type that a function expects, but it does not specify what the function does.
When the programmer defines the function, the definition of the function must be the same as its prototype declaration. If the programmer makes any mistake, the compiler flags an error message. The function prototype declaration statement is always terminated with a semi-colon.
Syntax: [quote]Return_type function_name (parameter_list);[/quote]
Ex:
float sum (float, int); float sum (float x, int y);
[quote]Note:
- If the function is not returning any value, and then specifies the return type as void.
- void means nothing.
- If the functions return type is void then we can’t return values.
[/quote]
Function Definition
A function definition is the complete description of a function. Actually, a function definition tells what a function does and how it performs. A function definition contains a function body (a block of statements) in addition to the function name, arguments list, and return type.
Syntax:
Return_value_type function_name(parameter_list2 ) { Local variable Declarations Statements return (expression); }
Example:
float sum (float x, float y) { float z; z=x+y; return (z); }
Call by Value and Address
There are two ways in which we can pass arguments to the function.
- Call by value
- Call by address
Call by Value: In this type value of actual arguments are passed to the formal arguments and the operation is done on the formal arguments. Any change made in the formal argument does not affect the actual arguments because formal arguments are a photocopy of actual arguments. Hence, when a function is called by the call or by value method, it does not affect the actual contents of the actual arguments. Changes made in the formal arguments are local to the block of the called function. Once control returns back to the calling function the changes made vanish.
Call by Address: in this type instead of passing values, addresses are passed. The function operates on addresses rather than values. Here the formal arguments are pointers to the actual arguments. In this type formal arguments point to the actual argument. Hence changes made in the arguments are permanent.
Using call by reference method function can return more than one value per call.
Built suitable examples.
About return statement
In c programming language we can use two types of return statements
- return
- return (expression)
The first type return does not return any values, it acts much as the closing brace of the function. When a return is encountered, the control is immediately passed back to the calling function.
When a value is returned, it automatically converts the function’s type.
Example:
#include <stdio.h> float sum(int v1,float v2) { return v1+v2; } int main() { int i; float f; i=sum(5,5); f=sum(5,5); printf("%d %f",i,f); return 0; }
[quote]Output:10 10.000000[/quote]
Here some more cases to consider
Calling | i(int) | f(float) |
sum(5,5); | 10 | 10.000000 |
sum(5,5,5); | Error Too many argument | |
sum(5); | Error required arguments missing | |
sum(7.5,7.5) | 14 | 14.500000 |
sum(7,7.5); | 14 | 14.500000 |
sum(7.5,7); | 14 | 14.000000 |
[quote]
Note:
When the function returns integer it is not required to declare it even if it defined later.
[/quote]
Function Declaration | Function calling |
int sum(int,int) ; | i1=sum(i2,i3); |
float sum(float,float); | f1=sum(f2,f3); |
char sum(char,int,float); | c1=sum(c2,i1,f1); |
void sum( ); or void sum(void); | sum(); |
void sum(int,char); | sum(i1,c1); |
float sum(char,int,float,float); | f1=sum(c1,i1,f2,f3); |
Types of functions
- There are two functions in C-language
Library functions
The library functions are a pre-defined set of functions. Their task is limited. A user can not understand the internal working of these functions. The user can only use the functions but can’t change or modify them.
User-defined functions
These functions allow the programmer to define their own functions according to the requirement of the program. The user has full scope to implement his/her own ideas in the function. The user certainly understands the internal working of the function.
Types of User Define function
A function, depending on whether arguments are present or not and whether a value is returned or not classified into four types.
- Function with no arguments and no return type.
- Function with arguments and no return type.
- Function with no arguments and one return value.
- Function with arguments and return type.
[quote]
Note:
- If the function return type other than void and returning a value to the calling place is optional.
- Even though the function is returning the value collecting the value also optional.
- Default return type to any function is int.
[/quote]
Function with no arguments and no return type
When a function has no arguments, it does not receive any data from the calling function. Similarly, when it does not return a value, the calling function does not receive any data from the called function. There is no data transfer between the calling function and called the function. The function is only executed and nothing is obtained. Such functions may be useful to print some messages, draw a line or split the line, etc.
Calling function | Analysis | Called function |
main() { |
No arguments are passed
No values are sent back |
abc() { ……; ……; ……; ……; } |
Example:
#include <stdio.h> void abc() { printf("\nhello xyz"); } int main() { abc(); printf("\nhello main"); return 0; }
[quote]
Output:
[/quote]
Function with arguments and no return type
Function receiving data from the calling function. But it does not return a value; the calling function receives data from the called function. And called function is does not returning any values. There is one direction data transfer between the calling function and called function.
Calling function | Analysis | Called function |
main() { |
Arguments are passed
No values are sent back |
abc(y) { ……; ……; ……; ……; } |
Example:
#include <stdio.h> int main() { void sum(int,int); sum(10,20); } void sum(int a, int b) { printf("sum of a,b=%d",a+b); }
[quote]
Output:
sum of a,b=30
[/quote]
Function with no arguments and return value
When a function has no arguments, it does not receive any data from the calling function. But called function returning the value back to the calling place. There is one direction data transfer between the called function and calling function.
Calling function | Analysis | Called function |
main() { |
No Arguments are passed
values are sent back |
abc() { int y=5; ……; ……; return y; } |
Example:
#include <stdio.h> int getNumber() { int n; printf("Enter a value: "); scanf("%d",&n); return n; } int main() { int i; i=getNumber(); printf("%d",i); return 0; }
[quote]
Output:
[/quote]
Function with arguments and return type
Function receiving data from the calling function, and called function returning the value to back to the calling place. There is two direction data transfer between the calling function and called function.
Calling function | Analysis | Called function |
main() { |
Arguments are passed
values are sent back |
abc() { int y=5; ……; ……; return y; } |
Example:
#include <stdio.h> int sum(int v1,int v2) { return v1+v2; } int main() { int i; i=sum(10,20); printf("%d",i); return 0; }
[quote]Output: 30 [/quote]
Formal arguments and Actual arguments
Parameters are used in three places, in a declaration, function call, and function definition.
The argument (parameter) used in prototypes (declaration) and function definitions are called formal arguments and those used in function calls are called actual arguments. An actual argument may be simple constants, variables or expressions.
- The formal and actual parameters must match exactly in type, order, and number.
- Any function is returning the value to the calling place it is done through the return statement.
- The return statement can use in two ways.
Recursion
When a called function calls another function a process of ‘chaining’ occurs. In C, it is possible for the functions to call themselves. A function is called ‘recursive’ if a statement within the body of a function calls the same function. Recursion is the process of defining something in teams of ‘itself’.
Exampe1:
/* Non-recursive function for calculating the factorial values of an integer */ #include <stdio.h> int fac ( int n) { int f=1,i; for ( i=n ; i>=1 ; i--) f=f*i; return(f); } int main() { int a,fact; printf("\nEnter any number: "); scanf("%d",&a); fact=fac(a); printf("Factorial value=%d",fact); return 0; }
[quote]
[/quote]
Example2:
/* Recursive function for calculating the factorial values of an integer */ #include <stdio.h> int fac(int n) { if (n >= 1) return n*fac(n-1); else return 1; } int main() { int a,fact; printf("\nEnter any number: "); scanf("%d",&a); fact=fac(a); printf("Factorial value=%d",fact); return 0; }
[quote]
[/quote]
Scope variables
Scope of a variable is defined as a vicinity or space within a program, where the value of a given variable can be accessed.
The area or block of the C program from where the variable can be accessed is known as the scope of a variable. The area or scope of the variable depends on its storage class i.e. where and how it is declared. There are four scope variables:
- Function
- File
- Block
- Function prototype
Block structure: Block generally refers to a segment within a program providing certain functionality to that program. The ways these blocks are organized are referred to as block structures.
A block may hold variables, structures, expressions, control structures, etc., which are necessary for a program. It initiates with an opening brace and terminates with a closing brace. A program can hold any number of blocks, also it is possible to insert a block within another block.
Library Functions: C has a large set of useful built-in library functions which are ready to be used in our programs. The function prototypes for these functions are available in general header files. Therefore the appropriate header file for a standard function must be included at the beginning of our programs.
Mathematical Functions
These functions are available in math.h
Function |
Description |
Prototyping |
Example |
abs fabs labs ceil floor pow Sqrt |
Returns the absolute value of an integer number Returns the absolute value of a floating point number Returns the absolute value of a long integer number Returns smallest integer value greater than or equal to a number Returns the largest integer value less than or equal to a number Returns the value of a raised to the power b. an error occurs if a =0 and b<= 0 or if a<0 and b is not an integer. Returns the square root of a number |
int abs (int num); double fabs(double num); long labs(long num); double ceil (double num); double floor(double num); double pow(double a, double b); double sqrt(double num); |
abs(-5)=5 fabs (3.2) = 3.2 labs(3.2L)=3.2 ceil (3.005)=4 floor (3.9999)=3.0 pow (2.0, 5.0)=32.0 sqrt(144.0) = 12 |
String Handling Functions
These functions are available in <string.h>
Function |
Description |
Prototyping |
Example |
strcpy strcat strlen strcmp |
strcpy (target, source) strcat (target, source) strlen (source) strcmp (str1, str2) |
Copies source string to target string and returns target. Concatenates source string to the end of the target and returns target. Returns the length of the source string. Compares two strings and returns values are: 0 – if str1==str2 <0 – if str1 < str2 >0 – if str1>str2 |
strcpy(s2,s1); strcat(s1,s2); l=strlen(s); r=strcmp (s1,s2); |
General Library Functions
These functions are available in stdlib.h
Function |
Description |
Prototyping |
Example |
srand Rand |
Creates the first seed for a pseudorandom number series. Seed is a variable that is used by the random number generator to generate next number series. Returns a pseudorandom integer in the range 0 to RAND_MAX. in ANSI/iso standard the RAND_MAX value is 32,767 |
Void srand (unsigned int seed); int rand (void); |
srand (920); rand(); |
The necessity of main() in C
- A C program consists of one or more functions. One of them must be a main() function.
- The main() function is a user-defined function which is called by the compiler to execute the program.
- In other words, the execution of a C program starts and ends with main().
- The main() function can call other functions to perform special tasks. Therefore every C program must include a main() function.
- Every function returns some value. The return value for main() void because it returns nothing.
User-defined Vs built-in functions
User-defined functions |
Built-in functions |
The functions that are defined by the programmers according to the requirements of the program are called “user-defined functions” These functions can be modified by the programmers i.e., they are modifiable. They are not predefined. These are written by the programmers. White space between the function names and parenthesis () causes an error. User-defined functions can be overloaded. The program is responsible for defining the user-defined functions, hence their definitions increase the programmer’s overhead. Not already available, hence are created when required. Their definitions can appear anywhere in a program They must be declared before they are used. Ex: display(); area(); etc.. |
A built-in function is commonly required functions that are not grouped together and are stored in a library. These functions are not modifiable They are predefined These are not written by the programmers. White spaces between the function names and parenthesis () are ignored in case of built-in functions Built-in functions cannot be overloaded. Programmer’s overhead is reduced here, as they are available as “ready-to-use” functions. Already available for the programmers to call. Their definitions appear in standard libraries. Declarations of the built-in functions are not required. Ex: cos(x), sqrt (x), sin(x), etc. |