Declaring a function

To declare a function, we should specify the function return type, function name and function parameters.


return_datatype function_name(parameters);

return type

How to select the return type?

When we don't want to return any value from the function, we should declare return type as void.


void function_name(parameters);

When we want to return an integer value from a function, declare return type as int. Similarly, for float, char and double.


int    function_name(parameters);
char   function_name(parameters);
float  function_name(parameters);
double function_name(parameters);

function name

We should give a meaningful function name. After function name we should append open and close bracket ( ).


If we want to write a program to add two numbers, we can declare function name as add or sum like below.


return_datatype add( parameters );
return_datatype sum( parameters );


Function parameter refers the input which are passed while calling the function.

we have to specify the parameters list inside the bracket ().


Let's declare a function which will have two integer input parameters and returns the sum of two integers.

sum will be a integer value, so declare return type as int.

we are going to calculate the sum of two numbers, so we can name it add or sum.

parameters will be two integers, so we can declare a function prototype like below,


int add(int num1, int num2);

parameter name is optional one but datatype of the parameter is mandatory. So, we can also declare the same prototype like below,


int add(int, int);

we can name the parameter anything while defining the function.

Parameter field is an optional one.

we can also declare a function without any parameter like below,


int fun();

Topics You Might Like