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

What are the syntax rules for C++ functions?

WBOY
Release: 2024-04-18 13:09:02
Original
380 people have browsed it

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) {
  // 函数体
  // 返回值(如果适用)
}
Copy after login

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;
}
Copy after login

Output:

阶乘结果:120
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template