Programming Functions

User-defined functions

A function is a block of code that performs a specific task.

C allows you to define functions according to your need. These functions are known as user-defined functions. For example:

Suppose, you need to create a circle and color it depending upon the radius and color. You can create two functions to solve this problem:

  • createCircle() function
  • color() function

Example: User-defined function

Here is an example to add two integers. To perform this task, we have created an user-defined addNumbers().

#include <stdio.h>
int addNumbers(int a, int b);         // function prototype

int main()
    int n1,n2,sum;

    printf("Enters two numbers: ");
    scanf("%d %d",&n1,&n2);

    sum = addNumbers(n1, n2);        // function call
    printf("sum = %d",sum);

    return 0;

int addNumbers(int a, int b)         // function definition   
    int result;
    result = a+b;
    return result;                  // return statement

Function prototype

A function prototype is simply the declaration of a function that specifies function’s name, parameters and return type. It doesn’t contain function body.

A function prototype gives information to the compiler that the function may later be used in the program.

Syntax of function prototype

returnType functionName(type1 argument1, type2 argument2, ...);

In the above example, int addNumbers(int a, int b); is the function prototype which provides the following information to the compiler:

  1. name of the function is addNumbers()
  2. return type of the function is int
  3. two arguments of type int are passed to the function

The function prototype is not needed if the user-defined function is defined before the main() function.

Calling a function

Control of the program is transferred to the user-defined function by calling it.

Syntax of function call

functionName(argument1, argument2, ...);

In the above example, the function call is made using addNumbers(n1, n2); statement inside the main() function.

Leave a Reply

Your email address will not be published. Required fields are marked *