WEB DEVELOPER SITE
PYTHONPHP7JAVA
 

C++ Functions


function is a set of statements that perform a task together. Every C++ program has at least one function, the main function main() , and all other simple functions can define other extra functions.

You can divide the code into different functions. How you divide code into different functions is up to you, but logically, partitioning is usually done by performing a specific task on each function.

The

functiondeclaration tells the compiler the name, return type, and arguments of the function. The function definition provides the actual body of the function.

The

C++ standard library provides a number of built-in functions that programs can call. For example, the function strcat() is used to concatenate two strings, and the function memcpy() is used to copy memory to another location.

Functions have many names, such as methods, subroutines, or programs, to name a few.

syntax

return_type function_name( parameter list )
{
   body of the function
}
  • function name It is name of function.
  • return-type Data type of the value returned by the function.
  • body function A collection of statements defining what the function does.
  • parameters When a function is invoked, you pass a value to the parameter. This value is referred to as actual parameter or argument. The parameter list refers to the type, order, and number of the parameters of a function.

Example

#include <iostream>

using namespace std;

void simplecode() {
    cout << "Hello world!";
}

int main() {
    simplecode();
}

The parameter list refers to the type, order, and number of the parameters of a function.



Run example»

Functions

A function declaration, or function prototype, tells the compiler about a function name and how to call the function.
#include <iostream>
using namespace std;

//Function declaration
void simplecode();

int main() {
  simplecode();

  return 0;
}

//Function definition
void simplecode() {
  cout << "Hello world!";
}

Function declaration is required when you define a function in one source file and you call that function in another file. In such case, you should declare the function at the top of the file calling the function.

Function Parameters

Formal parameters behave within the function similarly to other local variables. They are created upon entering the function, and are destroyed upon exiting the function.
void printSomething(int x) 
{
   cout << x;
}

Example You can pass different arguments to the same function.
int timesTwo(int x) {
   return x*2;
}

The function defined above takes one integer parameter and returns its value, multiplied by 2. We can now use that function with different arguments.
int main() {
    cout  << timesTwo(2)  << endl;
//output 4
 cout  	<<timesTwo(8)  << endl;
//output 16
    cout  <<timesTwo(54)  << endl;
//output 108
}

Multiple Parameters

You can define as many parameters as you want for your functions, by separating them with commas. Let's create a simple function that returns the sum of two parameters.
int addNumbers(int x, int y) {
 // code goes here
}

Now let's calculate the sum of the two parameters and return the result:
int addNumbers(int x, int y) {
  int result = x + y;
  return result;
}

then we call function
int addNumbers(int x, int y) {
  int result = x + y;
  return result;
}

int main() {
  cout  << addNumbers(20, 15);
  // Outputs 45
}
You can also assign the returned value to a variable.
int main() {
  int x = addNumbers(12, 6);
  cout  << x;
  // Outputs 18
}

The random function

random numbers is helpful in a number of situations, including when creating games, statistical modeling programs, and similar end products.

int main() {
  cout  << rand();
}

Random Number

A for loop can be used to generate multiple random numbers.
 int main() {
    for (int x = 2; x <= 20; x++) {
        cout  << rand()  << endl;
    }
}
//Output
41
18467
6334
26500
19169
15724
11478
29358
26962
24464
5705
28145
23281
16827
9961
491
2995
11942
4827

Run example»

The srand() Function

The srand() function is used to generate truly random numbers.

Changing the seed value changes the return of rand(). However, the same argument will result in the same output.

int main () {
    srand(15);

    for (int x = 2; x <= 8; x++) {
        cout  << 4 + (rand() % 2)  << endl;
    }
}


Run example»
//Output 5 5 4 4 5 4 4

Truly Random Numbers

A solution to generate truly random numbers, is to use the current time as a seed value for the srand() function.
This example will help use of the time() function to get the number of seconds on your system time, and randomly seed the rand() function (we need to include the header for it):
int main () {
  srand(time(0));

  for (int x = 2; x < = 14; x++) {
    cout  << 2 + (rand() % 2) << endl;
  }
}

Using this seed value will create a different output each time we run the program.

When defining a function, you can specify a default value for each of the
last parameters. If the corresponding argument is missing when you call a function,
it uses the default value.
int sum(int a, int b=15) {
    int result = a + b;
    return (result);
}




This assigns a default value of 15 to the b parameter.

int main() {
    int x = 8;
    int y = 15;

    //calling the function with both parameters
    int result = sum(x, y);
    cout  << result  << endl;
//OUTPUT 23
    //calling the function without b
    result = sum(x);
    cout  <<  result  << endl;
//OUTPUT 23
  return 0;
}

Using Default Arguments

int main() {
    cout  << volume()  << endl;
    cout  << volume(2)  << endl;
    cout  << volume(4, 5)  << endl;
    cout  << volume(6, 8, 5)  << endl;
}

Lambda functions and expressions

C++11 provides support for anonymous functions called Lambda functions (also known as Lambda expressions).

Lambda expressions treat functions as objects. Lambda expressions can be used like objects, such as assigning them to variables and passing them as arguments, and evaluating them like functions.

Lambda expressions are essentially similar to function declarations. The specific form of the Lambda expression is as follows:

[capture](parameters)->return-type{body}

For example:

[](int x, int y){ return x < y ; }

If there is no return value, it can be expressed as:

[capture](parameters){body}

For example:

[]{ ++global_x; } 

In a more complicated example, the return type can be explicitly specified as follows:

[](int x, int y) -> int { int z = x + y; return z + x; }

In this example, a temporary parameter z is created to store intermediate results. As with normal functions, the value of z is not preserved until the next time the unnamed function is called again.

If the lambda function does not return a value (such as void), its return type can be completely ignored.

The current scope variable can be accessed within the Lambda expression, which is the Closure behavior of the Lambda expression. Unlike JavaScript closures, C++ variables pass the difference between passing values and passing references. Can be specified by the previous []:

[]      // No variables are defined. Using an undefined variable raises an error.
[x, &y] // x is passed in by value (default), y is passed in by reference. 
[&]     //Any external variables that are used are implicitly referenced by reference. 
[=] // Any external variables being used are hidden It is quoted by value.
[&, x]  // x is explicitly referenced by value. The remaining variables are referenced by reference. 
[=, &z] // z is explicitly referenced by reference. The remaining variables are referenced by value. 

Another point to note. For [=] or[&]In the form of a lambda expression, the this pointer can be used directly. However, for the form of [], if you want to use the this pointer, you must explicitly pass in:

[this]() { this->someFunc(); }();

Function declaration

functiondeclaration tells the compiler the name of the function and how to call the function. The actual body of the function can be defined separately.

The function declaration includes the following sections:

return_type function_name( parameter list );

For the function max() defined above, the following is a function declaration:

int max(int num1, /span>int num2);

In the function declaration, the name of the parameter is not important, only the type of the parameter is required, so the following is also a valid declaration:

int max(int, int< /span>);

A function declaration is required when you define a function in one source file and call a function in another file. In this case, you should declare the function at the top of the file that called the function.