C 語言中的值傳遞是什麼?


值傳遞是指在 C 程式語言中作為引數傳送的值。

演算法

下面給出了一個演算法來解釋 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
", a);    printf("b value is: %d
", b);    printf("c value is: %d
", c);    printf("d value is: %d
", d);    return 0; }

輸出

執行上述程式時,會產生以下結果 −

a value is: 10
b value is: 15
c value is: 20
d value is: 25

更新於:17-Mar-2021

4K+ 瀏覽量

開啟你的 職業生涯

透過完成課程獲得認證

開始
廣告