web analytics

What are user defined functions? What are the elements of user defined functions?

User defined functions

Functions are blocks of codes to perform specific tasks and return the result. However it is not mandatory for a function to return something. Also a function can perform more than a single task. User defined functions are basic building blocks of a program and can be found in the basic structure of C program.

Functions can be classified into two categories, namely, library functions and user-defined functions. User defined functions are those functions which do not ship as C (or other language) library function. The user or the developer develops or writes the function as part of the program they are writing. These functions are not available unless defined on included.

Example

Here addNumbers() is an user defined function.

//declaring an user defined function which has been defined later
float addNumbers(float a, float b);

int main(){
     float result;
     
     /* calling user defined function from the main function */
     result = addNumbers(.5, .8);

     return 0;
     }

//defining an user defined function which has been declared earlier.
float addNumbers(float a, float b){
     return (a+b);
     }

Elements of User Defined Functions

In order to make use of an user defined function, we need to establish three elements, which are as follows

  1. Declaration
  2. Definition
  3. call

Function Declaration

Declaration of function is simply declaring the name of the function, the arguments and their types and the return type of the function. User needs to declare a function prior to the definition of the main() function when the definition of the function is written after the definition of the main() function. If the user writes the definition of the function prior to the definition of the main() function then it is not needed to declare the function explicitly.

//declaring an user defined function which has been defined later
float addNumbers(float a, float b);

Function Definition

Function definition includes the parts of the function declaration along with the body or code-block for the function. User can define a function before or after the main() function.

//defining an user defined function which has been declared earlier.
float addNumbers(float a, float b){
     return (a+b);
     }

Function Call

Calling an user defined function is similar to calling a library function, write the name of the function and provide the arguments. Also, if you need to store the returned data in a variable, then assign this call to a variable.

int main(){
     float result;
     
     /* calling user defined function from the main function */
     result = addNumbers(.5, .8);

     return 0;
     }

In this part of the example, we are calling the addNumbers() function and assigning it’s returned value to a variable result.

Read Next: What are the necessities or advantages of user defined functions?

Scroll to Top