C++에서 함수를 호출하는 세가지 방법
1. call by value
- 일반적으로 값을 인자로 전달하고 리턴으로 받는 방식
int sum(int a, int b)
{
return a + b;
}
sum(1 , 2);
2. call by address
- 함수 호출 시 인자로 변수의 주소를 전달하는 방법(리턴 없이 변수 변경)
void changeValue(int *a)
{
*a = 20;
}
int main()
{
int temp = 10;
changeValue(&temp);
std::cout << temp;
}
3. call by reference
void changeValue(int &a)
{
a = 20;
}
int main()
{
int temp = 10;
changeValue(temp);
std::cout << temp;
}
4. 배열의 call by reference
void changeValue(int (&a)[5])
{
for(int i = 0 ; i < 5 ; ++i)
{
a[i] = i;
}
}
int main()
{
int temp[5] = {0};
changeValue(temp);
for(int i = 0 ; i < 5 ; ++i)
{
std::cout << temp[i] << "\n";
}
return 0;
}
5. 배열의 call by reference 2
template <typename t, size_t S>
void changeValue(t (&a)[S])
{
for(int i = 0 ; i < S ; ++i)
{
a[i] = i;
}
}
int main()
{
int temp[5] = {0};
changeValue(temp);
for(int i = 0 ; i < 5 ; ++i)
{
std::cout << temp[i] << "\n";
}
return 0;
}
6. 배열의 call by reference 3
#include <iostream>
template <size_t S>
void changeValue(int (&a)[S])
{
for(int i = 0 ; i < S ; ++i)
{
a[i] = i;
}
}
int main()
{
int temp[5] = {0};
changeValue(temp);
for(int i = 0 ; i < 5 ; ++i)
{
std::cout << temp[i] << "\n";
}
return 0;
}
C++ 구현 시 call by reference가 권장되는 경우가 많다.
이때 활용할 수 있는 배열의 call by reference 예시를 작성했다.
다음엔 call by value, call by address, call by reference의 차이점에 대해 작성할 예정이다.
'기타 프로그래밍' 카테고리의 다른 글
[C++] 문자열의 거의 모든 것 (0) | 2022.05.12 |
---|---|
[C++] 표준 자료구조(컨테이너) vector, list, deque(queue) (0) | 2022.05.12 |
[C++] const vs constexpr | 상수 선언하기 (0) | 2022.05.11 |
[C++] C++ Core Guidelines (C++ 핵심 가이드라인) - P.2, P.3 (0) | 2022.02.22 |
[C++] C++ Core Guidelines (C++ 핵심 가이드라인) - P.1 (0) | 2022.02.20 |
댓글