how to call a function in a function c++ code example

Example 1: function call in c++

#include <iostream>
using namespace std;
//REMOVE COMMENTS TO USE VARIOUS FUNCTION CALLING METHODS
// function declaration
void swaper(int &,int&) ;// call  by reference
//void swaper(int *,int * );// call by address
//void swaper(int,int );//call by value


int main () {
   // local variable declaration:
   int a = 100;
   int b = 200;
   /* calling a function to swap the values using variable reference.*/
   swaper(a, b);// call by reference
   //swaper(&a, &b); //call by address
   //swaper(a, b); // call by value
   cout << "After swap, value of a :" << a << endl;
   cout << "After swap, value of b :" << b << endl;

   return 0;
}

//CALL BY refernce DEFINATION
void swaper(int &x, int &y) // x and y are ref variable..ie they are other name for a and b
{
   int temp;
   temp = x; //save the value as x which is ref for a
   x = y;    // put y into x
   y = temp; // put x into y
}
//CALL BY ADD DEFINATION
/*void swaper(int *x, int *y) {
   int temp;
   temp = *x; //save the value at address x
   *x = *y;    // put y into x
   *y = temp; // put x into y
*/

// CALL BY VALUE DEFINATION
/* void swaper(int x, int y) {
   int temp;
   temp = x; // save the value of local x
   x = y;    // put local y into local x
   y = temp; //put local x into local y
*/

Example 2: How to make a function in C++

//first lets create a function
/*void is for starting something, anything after void will be the name of your
function which will be followed by () */
void yourFunction() {
//your code will be here, anything here will be the code in the yourFunction
  cout << "Functions"
}
//now we have to go to our main function, the only function the compiler reads
int main() {
  myFunction(); //you call the function, the code we put in it earlier will be executed
  return 0;
}

Example 3: function declerations in C++

#include <iostream>
#include <stdlib.h>
#include <iomanip>
#include <fstream>
using namespace std;

void function_one(double, double, double);

int main() {
  double r1 = 1.0;
  double r2 = 2.0;
  double x = 0.0;
  function_one(r1, r2, x);
  return 0;
}

void function_one(double rmin, double rmax, double x0) {
  cout << "Function got called" << endl;
}

Tags:

Cpp Example