C

Call By Value, Call By Reference

pepega 2021. 10. 21. 16:43
///////////////////////
/////Call By Value/////
///////////////////////

#include <stdio.h>

void func(int n);

int main()
{
    int n = 10;     //메인함수 메모리의 변수n 에 10 입력
    func(n);        //func함수 메모리  내의 n안에 20입력
    printf("n의 값  : %d\n", n);    //메인 n > func함수 |  n -> 10 출력
    return 0;
}

void func(int n)
{
    n = 20;
}

//출처
//https://luckyyowu.tistory.com/9

./CallByValue
n의 값  : 10
///////////////////////////
/////Call By Reference/////
///////////////////////////

#include <stdio.h>

void swap(int*, int*);

int main()
{
    int a = 5;
    int b = 8;

    printf("swap 전 a의 값 : %d\n", a);
    printf("swap 전 b의 값 : %d\n", b);

    swap(&a, &b); //a, b 값 변경

    printf("swap 후 a의 값 : %d\n", a);
    printf("swap 후 b의 값 : %d\n", b);

    return 0;
}

void swap(int *x, int *y)
{
    int temp;   //바꾸기 위한 빈 공간 선언
    temp = *x;  //x(5)의 주소값을 temp에 저장
    *x = *y;    //y(8)의 주소값을 x의 주소에 저장
    *y = temp;  //temp(x의 주소)를 y의 주소에 저장
}

./CallByReference
swap 전 a의 값 : 5
swap 전 b의 값 : 8
swap 후 a의 값 : 8
swap 후 b의 값 : 5


출처
https://www.tutorialspoint.com/cprogramming/c_function_call_by_reference.htm

 

Function call by reference in C

Function call by reference in C The call by reference method of passing arguments to a function copies the address of an argument into the formal parameter. Inside the function, the address is used to access the actual argument used in the call. It means t

www.tutorialspoint.com