Home > Backend Development > C++ > body text

How to declare static functions in C++?

WBOY
Release: 2024-04-16 16:15:02
Original
668 people have browsed it

A static function is a function that does not belong to any class and is used to perform auxiliary tasks or provide global functionality. In C, static functions are declared with the following syntax: static type function_name(parameters), where the static keyword indicates that the function is static, type is the return value type, function_name is the function name, and parameters is the parameter list.

C++ 静态函数如何声明?

C Static function declaration

A static function is a function that does not belong to any class and is usually used to perform auxiliary tasks or provide global functionality. In C, a static function can be declared with the following syntax:

static type function_name(parameters) { ... }
Copy after login

where:

  • static keyword indicates that the function is static.
  • type is the function return value type, which can be any valid C data type.
  • function_name is the function name.
  • parameters is the function parameter list, which can be any number and type of parameters.
  • The function body contains the code to be executed.

Syntax example:

static int sum(int a, int b) {
  return a + b;
}
Copy after login

Practical case

Suppose we want to write a program that calculates the average grade of students. We can define a static function calculate_average to perform this task:

#include <iostream>

using namespace std;

static double calculate_average(int scores[], int size) {
  double sum = 0;
  for (int i = 0; i < size; i++) {
    sum += scores[i];
  }
  return sum / size;
}

int main() {
  // 定义学生成绩数组
  int scores[] = {85, 90, 75, 95};
  int size = sizeof(scores) / sizeof(int);

  // 调用静态函数计算平均成绩
  double average = calculate_average(scores, size);

  // 输出平均成绩
  cout << "平均成绩: " << average << endl;

  return 0;
}
Copy after login

In this example, the static function calculate_average is used to calculate the average of a set of scores in an array value and called through the main() function.

The above is the detailed content of How to declare static functions in C++?. 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