Computer >> Máy Tính >  >> Lập trình >> lập trình C

Gọi theo giá trị trong ngôn ngữ C là gì?

Truyền theo giá trị hoặc gọi theo giá trị được gửi dưới dạng đối số.

Thuật toán

Tham khảo thuật toán cho lệnh gọi theo giá trị.

Step 1: Enter any 2 numbers at runtime
Step 2: Read those two numbers from console
Step 3: Call the function swap with arguments is a call by value
Step 4: Go to called function
        swap(int a,int b)
Step 5: Print the numbers after swap

Ví dụ

Sau đây là chương trình C cho lệnh gọi theo giá trị -

#include<stdio.h>
void main(){
   void swap(int,int);
   int a,b;
   clrscr();
   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);
   getch();
}
void swap(int a,int b){
   int t;
   t=a;
   a=b;
   b=t;
}

Đầu ra

Khi chương trình trên được thực thi, nó tạo ra kết quả sau -

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