CodesJava

Easy learning with example program codes

CPP Functions

A function is a piece of code that can be used repeatedly in a CPP program. A function is mainly of two types:

  • Built in Functions; which are already defined in CPP Library.
  • User Defined Functions; which are created and defined by users.

 

Syntax:

Return_type functionName(parameters)

{

 code to be executed;

}

 

Rules for using Functions:

  • Void return type is used when nothing need to be returned from the function.
  • Functions can also be used to return value. Return type such as int, long, char etc. are used to return a value from the function of the given type.
  • A function starts with an opening curly brace ( { ) and ends with a closing curly brace ( } ).
  • Arguments are the variables, inside the parentheses, after the function name which is used to pass informations to functions.
  • For multiple arguments, comma should be used for separation.
  • Default argument value can also be specified in a function. If no argument is specified, the function will take the default argument.

 

Calling a Function in CPP:

In order to get the value returned from the function, the function need to be called in the program.

Syntax:

Variable_name = function_name (parameters_values);

 

Example:

#include <iostream.h>
using namespace std;
 
int writeMsg()
{
cout << "My First Program using Function!";
return 0;
}
int main()
{  
writeMsg();
return 0;
}

Output:

My First Program using Function!
Please follow and like us:
error
Posted in CPP   








Copyright © 2019 CodesJava DMCA.com Protection Status