ผ่านการอ้างอิงในภาษา C คือที่อยู่ซึ่งถูกส่งเป็นอาร์กิวเมนต์
อัลกอริทึม
อัลกอริทึมได้รับด้านล่างเพื่ออธิบายการทำงานของ pass by value ในภาษา C
START Step 1: Declare a function with pointer variables that to be called. Step 2: Declare variables a,b. Step 3: Enter two variables a,b at runtime. Step 4: Calling function with pass by reference. jump to step 6 Step 5: Print the result values a,b. Step 6: Called function swap having address as arguments. i. Declare temp variable ii. Temp=*a iii. *a=*b iv. *b=temp STOP
ตัวอย่างโปรแกรม
ต่อไปนี้เป็นโปรแกรม C เพื่อสลับตัวเลขสองตัวโดยใช้รหัสผ่านอ้างอิง -
#include<stdio.h>
void main(){
void swap(int *,int *);
int a,b;
printf("enter 2 numbers");
scanf("%d%d",&a,&b);
printf("Before swapping a=%d b=%d",a,b);
swap(&a, &b);
printf("after swapping a=%d, b=%d",a,b);
}
void swap(int *a,int *b){
int t;
t=*a;
*a=*b; // *a = (*a + *b) – (*b = * a);
*b=t;
} ผลลัพธ์
เมื่อโปรแกรมข้างต้นทำงาน มันจะให้ผลลัพธ์ดังต่อไปนี้ −
enter 2 numbers 10 20 Before swapping a=10 b=20 After swapping a=20 b=10
มาดูตัวอย่างอื่นเพื่อเรียนรู้เพิ่มเติมเกี่ยวกับการผ่านโดยการอ้างอิง
ตัวอย่าง
ต่อไปนี้เป็นโปรแกรม C ที่จะเพิ่มค่า 5 สำหรับการโทรทุกครั้งโดยใช้การโทรโดยการอ้างอิงหรือผ่านโดยการอ้างอิง
#include <stdio.h>
void inc(int *num){
//increment is done
//on the address where value of num is stored.
*num = *num+5;
// return(*num);
}
int main(){
int a=20,b=30,c=40;
// passing the address of variable a,b,c
inc(&a);
inc(&b);
inc(&c);
printf("Value of a is: %d\n", a);
printf("Value of b is: %d\n", b);
printf("Value of c is: %d\n", c);
return 0;
} ผลลัพธ์
เมื่อโปรแกรมข้างต้นทำงาน มันจะให้ผลลัพธ์ดังต่อไปนี้ −
Value of a is: 25 Value of b is: 35 Value of c is: 45