ํฐ์คํ ๋ฆฌ ๋ทฐ
๐ call-by-value VS call-by-reference
ํจ์๋ฅผ ํธ์ถํ ๋ ๋จ์ํ ๊ฐ์ ์ ๋ฌํ๋ ํํ์ ํจ์ํธ์ถ์ ๊ฐ๋ฆฌ์ผ Call-by-value๋ผ ํ๊ณ , ๋ฉ๋ชจ๋ฆฌ์ ์ ๊ทผ์ ์ฌ์ฉ๋๋ ์ฃผ์ ๊ฐ์ ์ ๋ฌํ๋ ํํ์ ํจ์ํธ์ถ์ call-by-reference๋ผ ํ๋ค.
[ call-by-value VS call-by-reference]
๐ ์์ 1)
๋ณ์ num์ ์ ์ฅ๋ ๊ฐ์ ์ ๊ณฑ์ ๊ณ์ฐํ๋ ํจ์๋ฅผ ์ ์ํ๊ณ , ์ด๋ฅผ ํธ์ถํ๋ main ํจ์๋ฅผ ์์ฑํด๋ณด์. ๋จ, ์ฌ๊ธฐ์๋ ๋ค์ ๋ ๊ฐ์ง์ ํํ๋ก ํจ์๋ฅผ ์ ์ํด์ผ ํ๋ค.
- call-by-value ๊ธฐ๋ฐ์ SquareByValue ํจ์
- call-by-reference ๊ธฐ๋ฐ์ SquareByReference ํจ์
SquareByValue ํจ์๋ ์ธ์๋ก ์ ๋ฌ๋ ๊ฐ์ ์ ๊ณฑ์ ๋ฐํํด์ผ ํ๋ฉฐ, SquareByReference ํจ์๋ ์ ์๊ฐ ์ ์ฅ๋์ด ์๋ ๋ณ์์ ์ฃผ์ ๊ฐ์ ์ธ์๋ก ๋ฐ์์ ํด๋น ๋ณ์์ ์ ์ฅ๋ ๊ฐ์ ์ ๊ณฑ์ ๊ทธ ๋ณ์์ ๋ค์ ์ ์ฅํด์ผ ํ๋ค.
๐คฆโ๏ธ ์๊ฐ ๊ณผ์
1. SquarByValue ํจ์๋ ๊ทธ๋ฅ ๋ฐ๋ ๊ฐ์ num * num ์ ์ด์ฉํ์ฌ ๋ง๋ค๋ฉด ๋ ๊ฒ ๊ฐ๊ณ Reference๋ ์ฃผ์๊ฐ์ ํ์ฉํ์ฌ ๋ง๋ค์. ๋จ, ๊ณ์ฐ์์ ์ฃผ์๊ฐ์ ๊ณฑํ๋๊ฒ์ด ์๋ ๋ณ์์ ์ฃผ์๊ฐ์ ๋ฃ์ด ๋ณ์๋ผ๋ฆฌ์ ๊ณฑ์ ๋ง๋ค์
๋ด๊ฐ ์๊ฐํ ๋ต
#include <stdio.h>
int SquareByValue(int num)
{
return num * num;
}
void SquareByReference(int *ptr)
{
int num = *ptr;
*ptr = num * num;
}
int main()
{
int num = 10;
printf("%d \n", SquareByValue(num));
SquareByReference(&num);
printf("%d \n", num);
return 0;
}
๐ ์์ 2)
์ธ ๋ณ์์ ์ ์ฅ๋ ๊ฐ์ ์๋ก ๋ค๋ฐ๊พธ๋ ํจ์๋ฅผ ์ ์ํด๋ณด์. ์๋ฅผ ๋ค์ด์ ํจ์์ ์ด๋ฆ์ด Swap3๋ผ ํ๋ฉด, ๋ค์์ ํํ๋ก ํจ์๊ฐ ํธ์ถ๋์ด์ผ ํ๋ค.
- Swap3(&num1,&num2,&num3);
๊ทธ๋ฆฌ๊ณ ํจ์ํธ์ถ์ ๊ฒฐ๊ณผ๋ก num1์ ์ ์ฅ๋ ๊ฐ์ num2์, num2์ ์ ์ฅ๋ ๊ฐ์ num3์, ๊ทธ๋ฆฌ๊ณ num3์ ์ ์ฅ๋ ๊ฐ์ num1์ ์ ์ฅ๋์ด์ผ ํ๋ค.
๐คฆโ๏ธ ์๊ฐ ๊ณผ์
1. ์ ์ฅ๋ ๊ฐ์ ๋ฐ๊ฟ์ผ ํ๋ ์๋ก์ด ๋ณ์ temp๋ฅผ ํ์ฉํ์ฌ ์๋ฅผ ๋์ ํด์ค๋ค.
2. ๋จ์ ๊ฐ ๋ณ๊ฒฝ์ด ์๋ ์ฃผ์๊ฐ์ ๋ณ๊ฒฝํ๊ธฐ ์ํด ์ฃผ์๊ฐ์ ์ ๊ทผํ๋ค. ์ฆ, ๋ณ์๋ฅผ ๋ฐ์๋์๋ ํฌ์ธํฐ ์ฃผ์๊ฐ์ ๋ฐ๋๋ค.
๋ด๊ฐ ์๊ฐํ ๋ต
#include <stdio.h>
int Swap3(int* ptr1, int* ptr2, int* ptr3)
{
int temp = *ptr1;
*ptr1 = *ptr2;
*ptr2 = *ptr3;
*ptr3 = temp;
}
int main()
{
int num1 = 10, num2 = 20, num3 = 30;
Swap3(&num1, &num2, &num3);
printf("%d %d %d", num1, num2, num3);
}
'์ธ์ด > C' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[C์ธ์ด] ํฌ์ธํฐ์ ํฌ์ธํฐ (0) | 2023.03.02 |
---|---|
[C์ธ์ด] ๋ค์ฐจ์ ๋ฐฐ์ด (0) | 2023.02.19 |
[C์ธ์ด] ํฌ์ธํฐ์ ๋ฐฐ์ด (1) (0) | 2023.02.16 |
[C์ธ์ด] ๋ฐฐ์ด์ ์ด์ฉํ ๋ฌธ์์ด ๋ณ์์ ํํ (0) | 2023.02.13 |
[C์ธ์ด] 1์ฐจ์ ๋ฐฐ์ด (0) | 2023.02.12 |