사자자리
[C++] 함수 본문
함수
하나의 특별한 목적의 작업을 수행하기 위해 독립적으로 설계된 코드의 집합
함수를 사용하려면?
1. 함수 정의 제공: 라이브러리
2. 함수 원형 제공: 라이브러리
3. 함수 호출
함수의 종류
1. return 값이 있는 함수
2. return 값이 없는 함수
#include <iostream>
using namespace std;
const float PIE = 3.14;
//return 값이 있는 함수
float circle(int r) {
return r * r * PIE;
}
//return 값이 없는 함수
void cheers(int n) {
for (int i = 0; i < n; i++) {
cout << "Cheers!" << endl;
}
}
int main() {
cheers(3);
cout << "원의 넓이: " << circle(4);
return 0;
}
<실행 결과>
Cheers!
Cheers!
Cheers!
원의 넓이: 50.24
매개변수와 인자
함수와 배열 포인터
#include <iostream>
using namespace std;
const int SIZE = 8;
int sumArr(int[], int);
int main() {
int arr[SIZE] = { 1, 2, 4, 8, 16, 32, 64, 128 };
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;
}
<실행 결과>
배열의 원소의 총 합: 255
#include <iostream>
using namespace std;
const int SIZE = 8;
int sumArr(int*, int*);
int main() {
int arr[SIZE] = { 1, 2, 4, 8, 16, 32, 64, 128 };
int sum = sumArr(arr, arr + 5);
cout << "배열의 1번째부터 5번째까지의 원소의 합: " << sum;
return 0;
}
int sumArr(int* begin, int* end) {
int total = 0;
int* ptr;
for (ptr = begin; ptr != end; ptr++) total += *ptr;
return total;
}
<실행 결과>
배열의 1번째부터 5번째까지의 원소의 합: 31
함수와 구조체
#include <iostream>
using namespace std;
const int minsPerHr = 60;
struct Time { //구조체 생성
int hours, mins;
};
Time sum(Time*, Time*);
void showTime(Time);
int main() {
Time day1 = { 5, 45 };
Time day2 = { 4, 55 };
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;
}
<실행 결과>
이틀간 소요 시간 : 10시간 40분 입니다.
재귀 함수
- 자기 자신을 호출하는 함수
- 호출의 연쇄를 끝내기 위한 장치가 없다면, 끊임없이 반복하게 된다.
void recurs(argument) {
//Code 1
if (condition) recurs(argument);
//Code 2
}
1. Code 1이 실행된다.
2. if문의 condition이 참이라면, recurs 함수는 다시 호출된다.
3. Code 1이 실행된다.
4. if문의 condition이 참이라면, recurs 함수는 다시 호출된다.
⋮
n. if문의 condition이 거짓이라면, Code 2가 실행된다.
n+1. recurs 함수가 다시 호출되느라 실행되지 못한 이전 Code 2가 실행된다.
n+2. recurs 함수가 다시 호출되느라 실행되지 못한 이전 Code 2가 실행된다.
⋮
m. 함수가 종료된다.
#include <iostream>
using namespace std;
void countDown(int n) {
cout << "Code 1: " << n << endl;
if (n > 0) countDown(n - 1); //자기 자신을 호출
cout << "Code 2: " << n << endl;
}
int main() {
countDown(5);
return 0;
}
<실행 결과>
Code 1: 5
Code 1: 4
Code 1: 3
Code 1: 2
Code 1: 1
Code 1: 0
Code 2: 0
Code 2: 1
Code 2: 2
Code 2: 3
Code 2: 4
Code 2: 5
함수를 지시하는 포인터
- 함수도 주소를 가지고 있다.
- 함수의 주소는 그 함수에 해당하는 기계어 코드가 저장된 메모리 블록의 시작 주소이다.
1. 함수의 주소를 얻는다.
2. 함수를 지시하는 포인터를 선언한다.
3. 함수를 지시하는 포인터를 사용하여 그 함수를 호출한다.
#include <iostream>
using namespace std;
int func(int n)
return n + 1;
}
int main() {
int (*ptr)(int); //int형 함수, int형 매개변수
ptr = func; //포인터에 함수의 주소(func) 저장
cout << (*ptr)(3) << endl; //3 + 1인 4 출력
}
'C++ > C++ 이론' 카테고리의 다른 글
[C++] 분할 컴파일: #ifndef & #endif (0) | 2022.08.17 |
---|---|
[C++] 함수의 활용 (0) | 2022.08.05 |
[C++] 조건문 if, switch / 논리연산자 (0) | 2022.07.27 |
[C++] 반복문 for, while, do while (0) | 2022.07.27 |
[C++] 포인터 / new와 delete 연산자 (0) | 2022.07.16 |
Comments