搜尋此網誌

2025年9月4日星期四

Default arguments

When defining a function, default arguments must be specified from right to left.

// ✅ Valid

void greet(string name, string greeting = "Hello");


// ❌ Invalid

void greet(string name = "User", string greeting);

If you try to set a default for a parameter on the left while leaving one on the right without a default, the compiler (or interpreter) won’t know how to match arguments during a function call. It creates ambiguity.


Correct example

#include <iostream>

using namespace std;


// Default argument is on the right

void greet(string name, string greeting = "Hello") {

    cout << greeting << ", " << name << "!" << endl;

}


int main() {

    greet("Alice");              // Uses default greeting: "Hello"

    greet("Bob", "Good morning"); // Uses custom greeting

    return 0;

}


Incorrect example

#include <iostream>

using namespace std;


// ❌ Invalid: default argument on the left

// This will cause a compilation error

void greet(string name = "User", string greeting);


int main() {

    greet("Alice", "Hi");

    return 0;

}

The compiler doesn’t know how to interpret greet("Alice")—is "Alice" the name or the greeting?


Function Declaration

  • What it is: A promise to the compiler that a function exists.
  • Purpose: Tells the compiler the function’s name, return type, and parameters—so it can be called before it’s defined.
  • No implementation: It doesn’t contain the actual code.
int add(int a, int b);  // Declaration only

Function Definition
  • What it is: The actual implementation of the function.
  • Purpose: Contains the code that runs when the function is called.
  • Includes body: Has the logic, statements, and return value.
int add(int a, int b) {
    return a + b;
}

Microsoft Copilot

沒有留言:

發佈留言