Home >Backend Development >C++ >How to use functions in c++
C function is an independent unit of code that performs a specific task and involves the following steps: declare the function, specifying the name, return type, and parameters; define the function, provide the function body and execution code; call the function, use its name and provide actual parameters.
Usage of functions in C
A function is an independent unit of code that performs a specific task. Using functions in C is very simple:
1. Declaring a function
The declaration of a function specifies the function's name, return type, and parameters. For example:
<code class="cpp">int sum(int a, int b);</code>
2. Define the function
The definition of the function provides the implementation of the function. It includes the function body, which contains the code to be executed. For example:
<code class="cpp">int sum(int a, int b) { return a + b; }</code>
3. Calling a function
To call a function, just use its name and provide the actual parameters. For example:
<code class="cpp">int result = sum(10, 20);</code>
Parameter passing
Function can pass parameters by value, reference or pointer.
Return type
A function can return a value or no value. Functions that do not return a value are called void functions. The type of the return value is specified in the function declaration.
Example
Here is a simple example of using a function in C:
<code class="cpp">#include <iostream> int main() { int a = 10; int b = 20; int result = sum(a, b); std::cout << "The sum is: " << result << std::endl; return 0; } int sum(int a, int b) { return a + b; }</code>
Output:
<code>The sum is: 30</code>
The above is the detailed content of How to use functions in c++. For more information, please follow other related articles on the PHP Chinese website!