Home  >  Article  >  Backend Development  >  What are the syntax rules for C++ functions?

What are the syntax rules for C++ functions?

WBOY
WBOYOriginal
2024-04-18 13:09:02345browse

The syntax format of C function is: returnType functionName(parameterList) {}, including three components: return type, function name and parameter list. An example of a specific function call is the factorial function that calculates factorial. The factorial result is obtained through loop accumulation.

C++ 函数的语法规则是什么?

C function syntax

Grammar format:

returnType functionName(parameterList) {
  // 函数体
  // 返回值(如果适用)
}

Among them:

  • returnType: Function return type, which can be any data type or void (no return value).
  • functionName: Function name, following C naming rules.
  • parameterList: Function parameter list, separated by commas. Each parameter includes data type and parameter name.

Practical case:

The following is a function that calculates the factorial of a number:

int factorial(int num) {
  int result = 1;
  for (int i = 1; i <= num; i++) {
    result *= i;
  }
  return result;
}

// 测试函数
int main() {
  int number = 5;
  int result = factorial(number);
  cout << "阶乘结果:" << result << endl;
  return 0;
}

Output:

阶乘结果:120

The above is the detailed content of What are the syntax rules for C++ functions?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn