The void
keyword, used in the previous examples, indicates that the function should not return a value. If you want the function to return a value, you can use a data type (such as int
, string
, etc.) instead of void
, and use the return
keyword inside the function:
int myFunction(int x) {
return 5 + x;
}
int main() {
cout << myFunction(3);
return 0;
}
// Outputs 8 (5 + 3)
Try it Yourself »
This example returns the sum of a function with two parameters:
int myFunction(int x, int y) {
return x + y;
}
int main() {
cout << myFunction(5, 3);
return 0;
}
// Outputs 8 (5 + 3)
Try it Yourself »
You can also store the result in a variable:
int myFunction(int x, int y) {
return x + y;
}
int main() {
int z = myFunction(5, 3);
cout << z;
return 0;
}
// Outputs 8 (5 + 3)
Try it Yourself »
截取页面反馈部分,让我们更快修复内容!也可以直接跳过填写反馈内容!