Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

Default Arguments ใน C++

ในบทช่วยสอนนี้ เราจะพูดถึง Default Arguments (อาร์กิวเมนต์เริ่มต้น) ใน C++

Default Arguments คืออาร์กิวเมนต์ที่มีค่าเริ่มต้นกำหนดไว้ในฟังก์ชัน หากผู้เรียกไม่ส่งค่ามา โปรแกรมจะใช้ค่าเริ่มต้นนั้นแทน

ตัวอย่างโค้ด

#include <iostream>
using namespace std;

// ฟังก์ชันที่มี default arguments
int sum(int x, int y, int z = 0, int w = 0) {
    return (x + y + z + w);
}

int main() {
    cout << sum(10, 15) << endl;        // ใช้ z=0, w=0
    cout << sum(10, 15, 25) << endl;    // ใช้ w=0
    cout << sum(10, 15, 25, 30) << endl; // ใช้ค่าทั้งหมด
    return 0;
}

เอาต์พุต

25
50
80

กฎสำคัญ

  • Default arguments ต้องอยู่ขวามือสุด ของรายการพารามิเตอร์
  • ไม่สามารถมี default argument อยู่ก่อน non-default argument ได้
  • ค่าเริ่มต้นสามารถเป็นค่าคงที่ ตัวแปร global หรือฟังก์ชันได้
  • ในการประกาศฟังก์ชัน (declaration) ให้ระบุ default argument ใน prototype