什麼是 C 語言中的按引用傳遞?


C 程式語言中的按引用傳遞是指作為引數傳送的地址。

演算法

下面列出一個演算法來解釋 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

讓我們再舉一個例子來詳細瞭解按引用傳遞。

示例

下面是使用按引用傳遞或按引用傳遞進行每次呼叫增值 5 的 C 語言程式。

 線上演示

#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
", a);    printf("Value of b is: %d
", b);    printf("Value of c is: %d
", c);    return 0; }

輸出

執行上述程式後,會生成以下結果 −

Value of a is: 25
Value of b is: 35
Value of c is: 45

更新於:2021 年 3 月 17 日

1K+ 檢視

開啟你的 職業

完成課程並獲得認證

立即開始
廣告