ความหมาย
Pass by Value คือการส่งค่าของตัวแปรเป็นอาร์กิวเมนต์ ฟังก์ชันจะสร้างตัวแปรใหม่ (copy) รับค่า การเปลี่ยนแปลงในฟังก์ชันไม่ส่งผลต่อตัวแปรต้นฉบับ
อัลกอริทึม Swap แบบ Pass by Value
START
Step 1: ประกาศฟังก์ชัน swap รับ int parameters
Step 2: ประกาศตัวแปร a, b
Step 3: รับค่า a, b
Step 4: เรียก swap(a, b) ส่งค่า
Step 5: พิมพ์ค่า a, b (ไม่เปลี่ยนแปลง)
Step 6: ฟังก์ชัน swap:
i. temp = a
ii. a = b
iii. b = temp
(เปลี่ยนแปลงเฉพาะ copy ภายในฟังก์ชัน)
STOPตัวอย่างโปรแกรมที่ 1: Swap แบบ Pass by Value (ไม่สำเร็จ)
#include <stdio.h>
void swap(int a, int b); // รับค่า (copy)
int main() {
int a, b;
printf("ป้อนตัวเลข 2 ตัว: ");
scanf("%d%d", &a, &b);
printf("ก่อน swap: a=%d, b=%d\\n", a, b);
swap(a, b); // ส่งค่า
printf("หลัง swap: a=%d, b=%d\\n", a, b); // ค่าเดิม!
return 0;
}
void swap(int a, int b) {
int t = a;
a = b;
b = t;
// a, b ที่เปลี่ยนคือ parameter ภายในฟังก์ชันเท่านั้น
}ผลลัพธ์
ป้อนตัวเลข 2 ตัว: 10 20 ก่อน swap: a=10, b=20 หลัง swap: a=10, b=20 <-- ไม่เปลี่ยนแปลง!
ตัวอย่างโปรแกรมที่ 2: Increment แบบ Pass by Value
#include <stdio.h>
int inc(int num) {
num = num + 5;
return num; // ต้อง return ค่ากลับ
}
int main() {
int a = 10;
int b = inc(a); // ส่งค่า a, ได้ค่ากลับมาเก็บใน b
int c = inc(b);
int d = inc(c);
printf("a = %d\\n", a); // 10 (ไม่เปลี่ยน)
printf("b = %d\\n", b); // 15
printf("c = %d\\n", c); // 20
printf("d = %d\\n", d); // 25
return 0;
}ผลลัพธ์
a = 10 b = 15 c = 20 d = 25
เมื่อไหร่ควรใช้ Pass by Value
- ข้อมูลขนาดเล็ก (int, float, char)
- ไม่ต้องการให้ฟังก์ชันแก้ไขตัวแปรต้นฉบับ
- ต้องการความปลอดภัยข้อมูล (data protection)
- Functional programming style
เมื่อไหร่ควรใช้ Pass by Reference
- ต้องการแก้ไขตัวแปรต้นฉบับ
- ส่ง structure/array ขนาดใหญ่ (ประหยัดหน่วยความจำและเวลา)
- ฟังก์ชันต้อง return หลายค่า
- ทำงานกับ dynamic memory
สรุป
C เป็นภาษา Pass by Value เท่านั้น แต่สามารถจำลอง Pass by Reference ได้โดยการส่ง pointer (address) ซึ่งเป็นที่อยู่ของตัวแปร