2 min read

A function is a named unit of a group of program statements that can be invoked from other parts of the program.

Function helps reduce the program size and avoid ambiguity.

FUNCTIONS In c++ functions are of 2 type:

types of functions in c-cpp

For eg- sqrt(), exit(), pow() etc

  1. User-defined functions:these are the functions which are created by user as per the requirement.

FUNCTION REQUIREMENTS

Using a function requires mainly 3 statements:

  1. Function definition
  2. Function prototype
  3. Function call

Let’s understand them

  • Function definition:A function must be defined before it is used anywhere in the program.

Data type of function and arguments are not necessary to be same.

But the return value is always of function’s type.

Syntax:

 type function-name (parameter list) 
 {
 // body of the function
 } 

Where type specifies data type (default is integer type).Then it have desired function name. The parameter list is a comma-seperated list of variables of a function. Also known as arguments.A function can have any number of arguments or can be without arguments.

Example:

 // function to add two integers
 int sum(int a, int b)
 {
 int c;
  c=a+b;
 return c;
 } 

A function definition must have a return type, until and unless it is of void type.A function can be declared before or after main function.

  • Function prototype : Also known as function declaration.It is the declaration of the function that tells the program about the type of value returned by the function and no. And types of arguments.

It looks same as function definition except it has no body.

Syntax:

 type function-name (parameter list); 

A function definition is not needed when the function definition appears before its calling function.

Example:

 
 int sum(int a, int b); 
  • Function call: A function is called in order to invoke or execute it. It is done by providing function-name along with the values/variables as parameters with which we want it to perform action.

Example:

 
 sum(3,5); 

If you liked my articles , please follow me on @priya123 to get latest articles and post by me.

Categories: Uncategorized

0 Comments

Leave a Reply