본 문서는 인프런의 [하루 10분|C++] 누구나 쉽게 배우는 C++ 프로그래밍 입문 강의를 공부하며 작성한 개인 노트입니다.
함수
1. 함수 정의 제공
2. 함수 원형 제공 - 함수의 데이터형, 이름, 파라미터 단위
3. 함수 호출
리턴값 - 리턴값이 있는 함수와 없는 함수로 나뉨
1. 리턴값이 있는 함수
typeName functionName(parameterList)
{
statement(s);
return value;
}
void functionName(parameterList)
{
statement(s);
return; //생략 가능
}
예시
#include <iostream>
using namespace std;
void cheers(int n);
float circle(int x);
int main()
{
// 함수 실행
}
void cheers(int n) {
// 함수 내용
}
float circle(int x) {
// 함수 내용
// return
}
매개변수, parameter
전달인자, argument - 실제로 함수를 호출할 때 함수에 전달되는 변수
#include <iostream>
using namespace std;
const int SIZE = 8;
int sumArr(int[], int);
int main() {
int arr[SIZE] = { 1, 2, 4, 8, 16 };
int sum = sumArr(arr, SIZE);
cout << "함수의 총 합은 " << sum << " 입니다.";
return 0;
}
int sumArr(int arr[], int n) {
int total = 0;
for (int i = 0; i < n; i++)
total += arr[i];
return total;
}
int arr[SIZE] = { 1, 2, 4, 8, 16 };
> arr은 &arr[0]
을 포인트하는 중원론적인 코딩: int*
로 대체
[]
)는 배열, 포인터 모두에 사용 가능...
int sumArr(int*, int);
int main() { ... }
int sumArr(int* arr, int n) {
int total = 0;
for (int i = 0; i < n; i++)
total += arr[i];
return total;
}
int[]
와 int*
의 차이int[]
를 파라미터로 받으면 sizeof arr
를 호출시 배열 전체의 크기int*
를 파라미터로 받으면 sizeoff arr
를 호출시 배열의 첫 원소의 크기구조체 vs. 배열
함수는 원본이 아닌 복사본을 대상으로 작업한다
하지만 구조체는 값으로 전달할 때 문제 > 구조체의 크기가 클 때 복사하는데 시간이 걸리고 메모리를 많이 사용함 > 성능저하
구조체는 주소/참조로 전달하자
#include <iostream>
using namespace std;
struct Time
{
int hours;
int mins;
};
const int minsPerHr = 60;
Time sum(Time*, Time*);
void showTime(Time);
int main() {
Time day1 = { 5, 45 };
Time day2 = { 4, 55 };
// day1 & day2의 주소 전달
Time total = sum(&day1, &day2);
cout << "이틀간 소요 시간: ";
showTime(total);
return 0;
}
Time sum(Time* t1, Time* t2) {
Time total;
total.mins = (t1->mins + t2->mins) % minsPerHr;
total.hours = t1->hours + t2->hours +(t1->mins +t2->mins) / minsPerHr;
return total;
}
void showTime(Time t1) {
cout << t1.hours << "시간, " << t1.mins << "분입니다." << endl;
sum
함수에 전달된 인자는 구조체가 아니라 구조체의 포인터임 > ->
로 구조체의 멤버에 접근Time*
> 구조체의 주소를 받음Time
> 구조체의 값을 받음재귀 호출 - 함수가 자기 자신을 호출
int main() {
void recurse(argumentList) {
// code #1
if (condition)
recurse(argumentList);
// code #2
}
}
condition
이 true
인 동안에는 code #2
는 실행되지 않는다condition
이 false
를 도달하면 code #2
가 호출 순서 역순으로 실행됨예시
void countDown(int n) {
cout << "Counting..." << n << endl;
if (n > 0)
countDown(n - 1);
cout << n << "번째 재귀함수" << endl;
}
n
이 0이 되었을 때 code #2
가 역순으로 실행됨출력결과
Counting...5
Counting...4
Counting...3
Counting...2
Counting...1
Counting...0
0번째 재귀함수
1번째 재귀함수
2번째 재귀함수
3번째 재귀함수
4번째 재귀함수
5번째 재귀함수
함수 또한 주소가 있음
int main() {
int (*pf) (int);
pf = func; // 함수의 주소 지정
cout << (*pf) (3) << endl;
}
int func(int n) {
return n + 1;
}
pf
로 함수 호출