C programming user defined functions


A function is a single comprehensive unit (self-contained block) containing a block of code that performs a specific task. In this tutorial, you will learn about c programming user defined functions.

c programming user defined functions

C programming user defined functions

In C programming user can write their own function for doing a specific task in the program. Such type of functions in C are called user-defined functions.

Let us see how to write C programming user defined functions.

Example: Program that uses a function to calculate and print the area of a square.

#include <stdio.h>
int square(int a);   //function prototype
int main()
{
  int x, sqr;
  printf("Enter number to calculate square: ");
  scanf("%d", &x);
  sqr = square (x);    //function call
  printf("Square = %d", sqr);
  return 0; 
}                     //end main

int square (int a)    //function definition
{
  int s;
  s = a*a;
  return s;  //returns the square value s
}            //end function square

Elements of user-defined function in C programming

There are multiple parts of user defined function that must be established in order to make use of such function.

Function Call


Here, function square is called in main

sqr = square (x);    //function call

c function call

Function declaration or prototype


int square(int a);   //function prototype

Here, int before function name indicates that this function returns integer value to the caller while int inside parentheses indicates that this function will recieve an integer value from caller.

Function definition


A function definition provides the actual body of the function.

Syntax of function definition

return_value_type function_name (parameter_list)
{   
   // body of the function
}

It consists of a function header and a function body. The function_name is an identifier.

The return_value_type is the data type of value which will be returned to a caller.

Some functions performs the desired task without returning a value which is indicated by void as a return_value_type.

All definitions and statements are written inside the body of the function.

Good Programming Practice
To avoid ambiguity, we should not use the same name for functions arguments and the corresponding parameters in the function definition.

 

Common Programming Errors
Function definition inside another function results in a syntax error. Remember semicolon at the end of function prototype.

 

Return statement


Return statement returns the value and transfer control to the caller.

return s;  //returns the square value s

c return statement

There are three ways to return control.

return;

The above return statement does not return value to the caller.

return expression;

The above return statement returns the value of expression to the caller.

return 0;

The above return statement indicate whether the program executed correctly.