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
multiply
that takes two integer parametersa
andb
and returns their product. - Inside the
main
function, we call themultiply
function with arguments5
and3
and store the result in theresult
variable. - Finally, we print the result using the
cout
object.
The output of this program would be:
SNIPPET
1The result is: 15
xxxxxxxxxx
20
using namespace std;
// Function declaration
int 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 definition
int multiply(int a, int b) {
return a * b;
}
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment