Chapter 5: Function

Definition

A function is a self-contained block of code i.e., a subprogram that can act on data and return a value.

How to write a function

$return\_type&space;function\_name(parameter_1,&space;parameter_2,\cdot&space;\cdot&space;\cdot&space;,&space;parameter_n)$

{

$\&space;\&space;\&space;\&space;statement_1;$

$statement_2;$

$statement_n;$

Example

int fun(int x, int y)

{

return (x+y);

}

Explanation:

• The name is fun
• It receives 2 values via the two parameters $x$ of int type and $y$ of int type
• It adds the contents of the variables $x$ and $y$ and produces a value of int type
• It returns the produced value
• Since the data type of the produced value and the return type must match, and in this case, the data type of the produced value is int, so the return type of the function is int

Every program has at least one function, main(). When a program starts, main() is automatically called that can call other functions, some of which might call still others. The details of operation within a function are invisible to the rest of the program.

Functions come in two varieties:

1. User-defined

2. Built-in (these are part of the compiler package supplied by the manufacturer for use)