Site icon TestingDocs.com

Structure of a C Function

Overview

In this tutorial, we will learn about the Structure of a C Function. There are three main parts of the function.

Let’s take a simple example C Function

/* Function Definition */
int sum(int x, int y) // Function Header
{
/* Local variables declaration -sum*/
int z = 0;
z = x + y; //Calculate the sum
return z;
} // end sum

Function Prototype

The function prototype is like a function declaration. The prototype of a function provides the basic information about a function which tells the compiler whether the function is used correctly or not. It contains the information the function header contains but can omit the function parameter names. We need to declare the function prototype before the main() function.

The prototype of the function in the above example can be like

int sum (int x, int y);

int sum (int, int );

Function Header

The function header specified the return type, name of the function, and the function parameters and their data types.

int sum(int x, int y)

The functional header in the example are :

 

Parameters of the function are enclosed in the parenthesis

Function Body

The function body starts with an open curly brace { and ends with }. The function body contains the programming statements.

Function Call

We can call the function from other parts of the C Program. For example, the main() can invoke the function to perform the task and may return the value of the function computation. The control transfers to the function. The function executes and returns to the caller function.

c = sum(a,b); // Function Call

In this example, we are calling the sum() function with the arguments a and b. The return value of the function would be stored in the variable c.

Example

We can find the big picture of all the parts working together in the sample program.

/**
**********************************
* Program Description:
* C Functions Demo
* Filename : userdefined.c
* C Tutorials - www.TestingDocs.com
*************************************
*/
#include<stdio.h>

/* Function Prototype */
int sum(int,int);

int main()
{
    /* Local variables declaration - main*/
    int a = 0, b = 0, c = 0;
    // Prompt user to enter a, b
    printf("Enter the number a = ");
    scanf("%d",&a);
    printf("Enter the number b = ");
    scanf("%d",&b);
    c = sum(a,b); // Function Call
    printf("The sum of %d , %d is = %d \n",a,b,c);
    return 0;
} // end main

/* Function Definition */
int sum(int x, int y)  // Function Header
{
    /* Local variables declaration -sum*/
    int z = 0;
    z = x + y; //Calculate the sum
    return z;
} // end sum



Exit mobile version