ค่าที่ส่งผ่านเรียกว่าค่าที่ส่งเป็นอาร์กิวเมนต์ในภาษาซี
อัลกอริทึม
อัลกอริทึมได้รับด้านล่างเพื่ออธิบายการทำงานของ pass by value ในภาษา C
START Step 1: Declare a function that to be called. Step 2: Declare variables. Step 3: Enter two variables a,b at runtime. Step 4: calling function jump to step 6. Step 5: Print the result values a,b. Step 6: Called function swap. 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; // all these statements is equivalent to
t=a; // a = (a+b) – (b =a);
a=b; // or
b=t; // a = a + b;
} // b = a – b;
//a = a – b; ผลลัพธ์
เมื่อโปรแกรมข้างต้นทำงาน มันจะให้ผลลัพธ์ดังต่อไปนี้ −
enter 2 numbers 10 20 Before swapping a=10 b=20 After swapping a=10 b=20
มาดูอีกตัวอย่างเพื่อทราบข้อมูลเพิ่มเติมเกี่ยวกับการส่งต่อค่า
ตัวอย่าง
ต่อไปนี้เป็นโปรแกรม C ที่จะเพิ่มค่า 5 สำหรับการโทรทุกครั้งโดยใช้การเรียกตามค่าหรือส่งผ่านค่า -
#include <stdio.h>
int inc(int num){
num = num+5;
return num;
}
int main(){
int a=10,b,c,d;
b =inc(a); //call by value
c=inc(b); //call by value
d=inc(c); //call by value
printf("a value is: %d\n", a);
printf("b value is: %d\n", b);
printf("c value is: %d\n", c);
printf("d value is: %d\n", d);
return 0;
} ผลลัพธ์
เมื่อโปรแกรมข้างต้นทำงาน มันจะให้ผลลัพธ์ดังต่อไปนี้ −
a value is: 10 b value is: 15 c value is: 20 d value is: 25