Objective C: Functions

Functions are defined as a separate block of codes in a program which can be reused whenever required.

A function has, a unique name followed by symbol ( ) which represents that it is a function, a return type, list of arguments (optional) and statements enclosed within curly braces { }.

We have been working with functions since from the start. The main function, from where execution of program begins has the following syntax:

int main(int argc, const argv[])

{

…….

…….statements;

…….

}

Where,

  • main( ) is the main function.
  • int is the return type of main function.
  • int argc, const argv[]  are the arguments passed inside main.
  •  { } represents starting and end of the function.

Any function has generally two parts namely, definition and calling.

  

  • Function definition

Definition is the body of function containing statements which are executed. The body of the function is enclosed in curly braces.

 Syntax:

return_type  nameofFunction ( arguments)

     {

       ….;

       ….statements;

       ….;

     }

 

  • Function Calling

A function executes whenever it is called by the main program. Therefore, function is called inside the main whenever required. A function is called by its name and parameters are passed from main function. Whenever a function is called, statements inside definition of function are executed and program counter is returned back to the main program.

 Syntax:

nameofFunction ( parameters);

 

Function prototype

Prototype means declaring a function before main in order to inform compiler that the specified function is used in the program. A prototype must be followed by a semicolon. A function prototype is required only if the function is given below the main.

Syntax:

          return_type  nameofFunction ( arguments);

A program using recursive function for calculating factorial is shown below:

In the above program,

Function definition  

fact(int x)

{

 if (x==0)

  return (1);

 else

  return (x * fact(x-1));

}

 

Function calling

f = fact(n);

The function is called from the main, function is executed and result is returned back to the main program.