Declaring a function

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


Syntax

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.

Example

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.

Example

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

Example

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

Example

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




parameters

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

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

Example

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,

Example

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,

Example

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,


Example

int fun();


Topics You Might Like