Detailed Explanation of C++ Function Variants

In C++, functions are not limited to the standard form of accepting a single parameter and returning a value; there are various variants. Below, we will detail the three types of function variants mentioned in section 2.4.2.

1. Multi-parameter Functions

Some functions require multiple parameters to complete more complex tasks.

#include <iostream>
#include <cmath>  // Includes the pow() function

using namespace std;

// Multi-parameter function example: Calculate rectangle area
double calculateRectangleArea(double length, double width) {
    return length * width;
}

// Multi-parameter function example: Display student information
void displayStudentInfo(string name, int age, double grade) {
    cout << "Name: " << name << endl;
    cout << "Age: " << age << endl;
    cout << "Grade: " << grade << endl;
}

int main() {
    // Using the pow function from the math library (two parameters)
    double result = pow(5.0, 8.0);  // Calculate 5 raised to the power of 8
    cout << "5 raised to the power of 8 = " << result << endl;
    
    // Using custom multi-parameter function
    double area = calculateRectangleArea(10.5, 8.2);
    cout << "Rectangle area: " << area << endl;
    
displayStudentInfo("Zhang San", 20, 88.5);
    
    return 0;
}

2. No-parameter Functions

Some functions do not require any input parameters.

#include <iostream>
#include <cstdlib>  // Includes the rand() function
#include <ctime>    // Includes the time() function

using namespace std;

// No-parameter function example: Get current time string
string getCurrentTime() {
    time_t now = time(0);
    return ctime(&now);
}

// No-parameter function example: Display menu
void displayMenu() {
    cout << "===== Main Menu =====" << endl;
    cout << "1. Start Game" << endl;
    cout << "2. Settings" << endl;
    cout << "3. Exit" << endl;
    cout << "==================" << endl;
}

int main() {
    // Using the rand function from the standard library (no parameters)
    srand(time(0));  // Set random seed
    int randomNum = rand();  // Generate random number, no parameters needed
    cout << "Random number: " << randomNum << endl;
    
    // Using custom no-parameter function
    cout << "Current time: " << getCurrentTime();
    displayMenu();
    
    return 0;
}

3. No-return Functions

Some functions only perform operations without returning any value.

#include <iostream>
#include <iomanip>  // Includes formatting functions like setprecision

using namespace std;

// No-return function example: Format and display amount
void bucks(double amount) {
    cout << fixed << setprecision(2);  // Set to two decimal places
    cout << "$" << amount << endl;
}

// No-return function example: Print separator line
void printSeparator(int length, char symbol) {
    for (int i = 0; i < length; i++) {
        cout << symbol;
    }
    cout << endl;
}

// No-return function example: Handle user login
void loginUser(string username, string password) {
    // Simulate login verification process
    cout << "Verifying user " << username << "..." << endl;
    
    // Actual verification logic should be here
    if (username == "admin" && password == "123456") {
        cout << "Login successful!" << endl;
    } else {
        cout << "Username or password incorrect!" << endl;
    }
    
    // Note: This function does not return any value
}

int main() {
    // Using no-return function
    bucks(1234.56);        // Displays: $1234.56
    bucks(23.5);           // Displays: $23.50
    
    printSeparator(30, '*');  // Print 30 asterisks as a separator
    cout << "System Report" << endl;
    printSeparator(30, '-');  // Print 30 dashes as a separator
    
    loginUser("admin", "123456");
    
    // Note: No-return functions cannot be used in expressions
    // double balance = bucks(100.0);  // Error! bucks does not return a value
    
    return 0;
}

4. Comprehensive Example

#include <iostream>
#include <string>

using namespace std;

// 1. Multi-parameter and return value
double calculateBMI(double weight, double height) {
    return weight / (height * height);
}

// 2. Multi-parameter but no return value
void displayHealthStatus(string name, double bmi) {
    cout << name << "'s Body Mass Index (BMI): " << bmi << endl;
    
    if (bmi < 18.5) {
        cout << "Underweight" << endl;
    } else if (bmi < 24) {
        cout << "Normal weight" << endl;
    } else if (bmi < 28) {
        cout << "Overweight" << endl;
    } else {
        cout << "Obese" << endl;
    }
}

// 3. No-parameter but return value
string getSystemVersion() {
    return "v2.4.2";
}

// 4. No-parameter and no return value
void showWelcomeMessage() {
    cout << "=== Health Management System " << getSystemVersion() << " ===" << endl;
}

int main() {
    // Demonstrate the use of various function variants
    showWelcomeMessage();  // No-parameter no return value
    
    string userName = "Li Si";
    double weight = 70.5;  // kg
    double height = 1.75;  // m
    
    // Multi-parameter with return value
    double bmi = calculateBMI(weight, height);
    
    // Multi-parameter no return value
    displayHealthStatus(userName, bmi);
    
    return 0;
}

Key Points Summary:

  1. Multi-parameter Functions: Use commas to separate multiple parameters, allowing for more complex logic
  2. No-parameter Functions:
  • Use<span>void</span> to explicitly declare or have no parameter list
  • Must have parentheses when called:<span>functionName()</span>
  • No-return Functions:
    • Return type is<span>void</span>
    • Cannot be used in assignment statements or expressions
    • Typically used to perform certain operations (e.g., output, modify global variables, etc.)

    These function variants make C++ programming more flexible, allowing for the selection of appropriate function forms to organize code based on different needs.

    Leave a Comment