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.


return_type function_name ( parameters )

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 );
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.



//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
    printf("Enter an integer to find its square: ");
    result = square(num);    //assigning the value returned by the square function
    printf("Enter two numbers to find their sum: ");
    scanf("%f %f",&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;


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


C Programming

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