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

Call by Value (ส่งค่า) ในภาษา C คืออะไร

Call by value = ส่งค่าตัวแปรไปให้ฟังก์ชัน (สร้าง copy) ฟังก์ชันแก้ไขไม่ส่งผลต่อตัวแปรต้นฉบับ

อัลกอริทึม

Step 1: รับ 2 ตัวเลข
Step 2: เรียก swap(a, b) แบบ call by value
Step 3: ในฟังก์ชัน swap สลับค่า local copy
Step 4: พิมพ์ค่าหลัง swap (ค่าเดิมไม่เปลี่ยน)

โปรแกรม

#include <stdio.h>
void swap(int a, int b) {
    int t = a;
    a = b;
    b = t;
}
void main() {
    int a, b;
    printf("enter 2 numbers: ");
    scanf("%d %d", &a, &b);
    printf("Before swapping a=%d b=%d\n", a, b);
    swap(a, b);
    printf("After swapping a=%d b=%d\n", a, b);
}

ผลลัพธ์

enter 2 numbers: 10 20
Before swapping a=10 b=20
After swapping a=10 b=20

สรุป: ค่า a, b ใน main ไม่เปลี่ยน เพราะส่งแค่ copy