Function Syntax
In C++, functions allow us to group a set of statements together and execute them whenever we need to. They provide modularity and reusability to our code.
Here's an example of a function in C++:
SNIPPET
1#include <iostream>
2using namespace std;
3
4// Function declaration
5int multiply(int a, int b);
6
7int main() {
8 // Function call
9 int result = multiply(5, 3);
10
11 // Print the result
12 cout << "The result is: " << result << endl;
13
14 return 0;
15}
16
17// Function definition
18int multiply(int a, int b) {
19 return a * b;
20}In this example:
- We declare a function
multiplythat takes two integer parametersaandband returns their product. - Inside the
mainfunction, we call themultiplyfunction with arguments5and3and store the result in theresultvariable. - Finally, we print the result using the
coutobject.
The output of this program would be:
SNIPPET
1The result is: 15xxxxxxxxxx20
using namespace std;// Function declarationint multiply(int a, int b);int main() { // Function call int result = multiply(5, 3); // Print the result cout << "The result is: " << result << endl; return 0;}// Function definitionint multiply(int a, int b) { return a * b;}OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment


