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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP