C Functions

A function is a set of instructions that performs a specific task. Function are called whenever needed which allows programmers to produce shorter and maintainable code. C provides support of both built-in functions and user-defined functions.

Syntax

return_type function_name ( parameters )
{
   //body
}

In C and C++, functions are required to have a prototype if they are defined after the main() function. The main function is the entry point of a program. The syntax for the function prototype is given below.

Function Prototype Syntax

return_type function_name ( parameters );
//or
return_type function_name ( data_type );

Structure of a Function

Functions can be divided into four parts:

  1. Function Name: The name of the function. Function calling is done by writing function name(argument).
  2. Function Body: The statements inside a function which peforms a particular task.
  3. Return Type: A function may or may not return a value. If you want a function to not return a value then simply put a void before the function name. To return a value of a type say int, write int before the function name. In the function body a return statement is required to return the value.
  4. Parameters: A function may require some value to work, for example, to calculate the area of a circle, length of the radius is required. Parameters are used to retrieve values when they are being called. Parameters are optional.

The following program shows the usage of functions in a program.

Code

#include<stdio.h>

//function prototype
void print_hello();
int square(int);
float sum(float,float);

int main(void)    //main function
{
    int num,result;
    float num1,num2;
    
    //function call
    print_hello();
    
    printf("Enter an integer to find its square: ");
    scanf("%d",&num);
    result = square(num);    //assigning the value returned by the square function
    printf("%d\n",result);
    
    printf("Enter two numbers to find their sum: ");
    scanf("%f %f",&num1,&num2);
    printf("%f\n",sum(num1,num2));

    return 0;    //A convention. 0 means successful execution.
}

//function definition
void print_hello()
{
    int val = 1;    //Local variable
    printf("Hello agent %d\n",val);
}

int square(int x)
{
    return x*x;
}

float sum(float x,float y)
{
    return x+y;
}

Output

Hello agent 1
Enter an integer to find its square: 5
25
Enter two numbers to find their sum: 23.5 1.5
25.000000

Trending

C Programming

Remember to follow community guidelines and don't go off topic.