导航菜单

函数

C++ / 函数

28%
函数定义与声明
// 函数声明(原型)
int add(int a, int b);
void printMessage(string msg = "Hello");  // 带默认参数
double calculateArea(double radius);

// 函数定义
int add(int a, int b) {
    return a + b;
}

void printMessage(string msg) {
    cout << msg << endl;
}

double calculateArea(double radius) {
    const double PI = 3.14159;
    return PI * radius * radius;
}

// 内联函数
inline int max(int a, int b) {
    return (a > b) ? a : b;
}

// 带有多个返回值的函数(使用引用参数)
void getMinMax(const vector<int>& numbers, int& min, int& max) {
    if (numbers.empty()) return;
    
    min = max = numbers[0];
    for (int num : numbers) {
        if (num < min) min = num;
        if (num > max) max = num;
    }
}