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\n", a);
printf("Value of b is: %d\n", b);
printf("Value of c is: %d\n", c);
return 0;
} 출력
위의 프로그램이 실행되면 다음과 같은 결과가 생성됩니다 -
Value of a is: 25 Value of b is: 35 Value of c is: 45