按值传递被称为在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; // 所有这些陈述等同于
t=a; // a =(a + b)–(b = a);
a=b; // 或者
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