C Programming User Defined Functions

C Programming User Defined Functions

The use of user-defined functions allows a large program to be broken down into a number of smaller, self-contained components, each of which has some unique, identifiable purpose. The repeated instruction can be placed within a single function, which can then be accessed whenever it is needed.

Moreover, a different set of data can be transferred to the function each time it is accessed. Thus, the use of a function avoids the need for redundant programming of the same instructions.

A function can be executed from anywhere within a program. Once the function has been executed, control will be returned to the point from which the function was accessed.

Functions contains special identifiers called parameters or arguments through which information is passed to the function and from functions information is returned via the return statement.

Syntax of User Defined Function

A function declaration specifies function’s name, parameters and return type. It doesn’t contain function body. function declaration also known as function prototype or function signature. It gives information to the compiler that the function may later be used in the program.

Download Code: user-defined-function-1.c (11 downloads)

In the above example, we have three function declaration , first function is void showlines(); which has not parameter and no return value. second function is void shownumbers(int n); which takes single parameter and no return value. third function is void findmax(int a,int b,int c) (); which takes three parameter and return value single value. The function prototype is not needed if the user-defined function is defined before the main() function.

Function definition

Function definition contains the block of code to perform a specific task. It provides the actual body of the function.

Syntax of function definition

Function call

When a function is called, the control of the program is transferred to the function definition. code inside the body of a function starts executing. then actual parameter values , get copied on formal parameters of function.

user-defined-function-1-formal-parameters-explain
user-defined-function-1

Function with return value

The return statement terminates the execution of a function and returns a value to the calling function. The program control is transferred to the calling function after return statement. Here main function is calling function and findmax is called function.

In the above example, the value of variable a or b is returned to the variable result in the main() function.

Download code: user-defined-function-2.c (9 downloads)

 

User Defined Function – Compare Two String using Pointer