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

Call by Reference (ส่งที่อยู่) ในภาษา C คืออะไร

Call by reference = ส่ง address ของตัวแปรไปให้ฟังก์ชัน (ใช้ pointer) ฟังก์ชันแก้ไขค่าจริงได้

โปรแกรม

#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); // ส่ง address
    printf("After swapping a=%d b=%d\n", a, b);
}

ผลลัพธ์

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

สรุป: ค่า a, b ใน main เปลี่ยนจริง เพราะส่ง address ไปให้ฟังก์ชัน