Chapter 5: Function


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 function\_name(parameter_1, parameter_2,\cdot \cdot \cdot , parameter_n)


    \ \ \ \ statement_1;





int fun(int x, int y)


    return (x+y);



  • 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)