cpp define function
Here is an example of defining a function in C++:
#include <iostream>
// Function declaration
int add(int a, int b);
int main() {
int num1 = 5;
int num2 = 10;
int sum = add(num1, num2);
std::cout << "The sum is: " << sum << std::endl;
return 0;
}
// Function definition
int add(int a, int b) {
return a + b;
}
Explanation:
The first line
#include <iostream>
is a preprocessor directive that includes the input/output stream library in our program. This library provides functionality for input and output operations.The next line
int add(int a, int b);
is a function declaration. It tells the compiler that there is a function namedadd
which takes two integer parametersa
andb
, and returns an integer value.The
main
function is the entry point of the program. It is where the execution of the program starts.Inside the
main
function, two integer variablesnum1
andnum2
are declared and assigned values5
and10
respectively.The
add
function is called withnum1
andnum2
as arguments, and the return value is stored in thesum
variable.The
std::cout
statement is used to output the result to the console. It prints the string "The sum is: " followed by the value ofsum
.The
return 0;
statement indicates the end of themain
function and the successful execution of the program.Finally, outside the
main
function, theadd
function is defined. It takes two integer parametersa
andb
, and returns the sum ofa
andb
.
This is a basic example of defining a function in C++. The function declaration informs the compiler about the existence of the function, and the function definition provides the implementation of the function.