< C++ Tutorial

C++ functions

← Previous Next →


A function is a block of program code which deals with a specific task. Making functions is a way of isolating one block of code from other independent blocks of code.

Functions serve two purposes:

  • They help in dividing big code into manageable smaller code blocks.
  • They help in avoiding repetation of same code. User can call function at multiple places for same operation.

How to use function:

  • Function prototype declaration
  • Function definition
  • Function call

Function prototype Declaration

Syntax:

 return-type function-name (parameter-list); 

Example :

int sum(int a, int b); // <-- Function prototype declaration

Function Definition

Syntax:

return-type function-name (parameter-list)
{
    // block of code
    return value ;
}

Example:

int sum(int a, int b)
{
    int c = a+b;
    return c;
}

Function Call

Syntax:

function-name(parameter-list);

Example:

int main()
{
  sum(10,20); // <-- function call
  return 0;
}

Note: When calling any function , function declartion or function definition must be done before it.

Full Example :

int sum(int a, int b); //<-- function declaration

// Function definition 
int sum(int a, int b)
{
   return (a+b);
}

int main()
{
  int c = sum(10,20); // <-- function call

  printf("%d\n", c);
  return 0;
}
← Previous Next →