C++ Functions: Complete Guide
In C++, the ways to use functions include defining functions, declaring functions, invoking functions, and passing arguments.
- Function definition: The general syntax for defining a function in C++ is:
返回类型 函数名(参数列表) {
// 函数体
}
For example,
As an illustration,
int add(int a, int b) {
return a + b;
}
- Declare a function: If a function is defined after the main function, it needs to be declared beforehand. The syntax for declaring a function is:
返回类型 函数名(参数列表);
For example:
int add(int a, int b);
- Call function: when calling a function, use the function name and a list of parameters. For example:
int result = add(3, 4);
- Passing parameters: You can pass parameters to a function by value, by reference, or by pointer. For example:
Pass by value:
void modify(int a) {
a = a + 1;
}
int num = 5;
modify(num);
// num的值仍然是5
Quote transmission:
void modify(int &a) {
a = a + 1;
}
int num = 5;
modify(num);
// num的值变为6
Pass by reference:
void modify(int *a) {
*a = *a + 1;
}
int num = 5;
modify(&num);
// num的值变为6
By using these methods, you can correctly define, declare, and call functions in C++ while passing parameters.