To make it easier to understand and correct the text of programs, you can allocate its fragments into separate routines.

The same is done with repeated fragments containing a tangible number of lines of program text.

Such fragments are written below the main() function after its last curly brace.

They are given a name, equipped with incoming arguments and a return value.

Example.

Output text to the message window, depending on the code passed to the subroutine.


int main()

{

   cout << "String from function with arg 1 = " << get_string(1) << ", the same, but with arg 2 = " << get_string(2);

}

// function declaration, takes the argument arg - an integer.

// returns a string value.

string get_string(int arg)

{

   string sresult;

   if (arg == 1)   // if arg eq 1

   {

      sresult = "string 1";  // then assign this value to the sresult variable.

   }

   else if (arg == 2) // if arg is eq 2

   {

      sresult = "string 2";

   }

   else  // if it not 1 and no 2, than with all other values

   {

      sresult = "string N";  // assign to variable sresult this value.

   }

   return sresult;  // return as result of the function content of the sresult variable.

}


Several variables (arguments) can be passed to the subroutine at once. Then they are written separated by commas.

Example.

Declare a function that takes two integers and one floating-point number as arguments, and returns a floating-point value.


double my_func(int a, int b, double c)

{

   return 10;

}


Due to the fact that the C++ text has a high execution speed, you can create any number of your own functions.