본문 바로가기
c++ 기초

12) 함수

by BitsrimAcrux 2024. 12. 29.
#include <iostream>

using namespace std;

int func1(int a); // 함수 원형 선언, 반환값 있는 함수
void func2(int a); //반환값 없는 함수

int main() {
    int a = 2;
    cout << func1(a) << func2(a) << endl;

    return 0;
}

int func1(int a) {
    return a + a;
}

void func2(int a) {
    cout << a + a;
}

float func(int a); 에서 반환값이 정수가 나와도 자동으로 실수로 변환


함수 매개변수로 배열 사용

#include <iostream>

using namespace std;

const int SIZE = 4;

int sumarr(int[], int n = 10); // 매개변수들
                  // sumarr(arr) 따로 값이 없을 때 디폴트 매개변수로 10이 전달됨
                  // 디폴트 매개변수들은 꼭 맨 오른쪽에 있어야 함 int n=10, int x 안됨

int main() {

	int arr[SIZE] = { 1, 2, 3, 4 };
	int s = sumarr(arr, SIZE); // 실제 전달되는 인자들, arr는 arr[0]의 주소와 같음
                        
	cout << s;

	return 0;
}

int sumarr(int arr[], int n) { //함수 원형에서 (int*, int)라 썼으면 (int* arr, int n)라 써도 됨
	int total = 0;

	for (int i = 0; i < n; i++) {
		total += arr[i];
	}
	return total;
}

배열 시작, 끝 주소 인자로 전달

#include <iostream>

using namespace std;

const int SIZE = 4;

int sumarr(int*, int*);

int main() {

	int arr[SIZE] = { 1, 2, 3, 4 };

	int sum = sumarr(arr, arr + SIZE); // 4번쨰 인덱스의 값까지 더하고 5번째는 안 더하고 끝남
	cout << SIZE << " 번째 인덱스까지 합" << sum << endl;

	sum = sumarr(arr, arr + 3);
	cout << "세 번째 인덱스까지 합 " << sum;
	return 0;
}

int sumarr(int* begin, int* end) {

	int total = 0;
	int* p;

	for (p = begin; p != end; p++) {
		total += *p;
	}

	return total;
}

함수와 구조체

// 값 전달
#include <iostream>

using namespace std;

struct Time {
	int hour;
	int min;
};

Time sum(Time, Time);

int main() {
	Time t1, t2, t3;
	cout << "시간 : ";
	cin >> t1.hour;
	cout << "분 : ";
	cin >> t1.min;

	cout << "시간 : ";
	cin >> t2.hour;
	cout << "분 : ";
	cin >> t2.min;

	t3 = sum(t1, t2);

	cout << "총 시간 " << t3.hour << "시간 " << t3.min << "분";

	return 0;
}

Time sum(Time t1, Time t2) {
	Time total;

	total.min = (t1.min + t2.min) % 60;
	total.hour = t1.hour + t2.hour + (t1.min + t2.min) / 60;

	return total;
}
// 주소 전달
#include <iostream>

using namespace std;

struct Time {
	int hour;
	int min;
};

Time sum(Time*, Time*);

int main() {
	Time t1, t2, t3;
	cout << "시간 : ";
	cin >> t1.hour;
	cout << "분 : ";
	cin >> t1.min;

	cout << "시간 : ";
	cin >> t2.hour;
	cout << "분 : ";
	cin >> t2.min;

	t3 = sum(&t1, &t2);

	cout << "총 시간 " << t3.hour << "시간 " << t3.min << "분";

	return 0;
}

Time sum(Time* t1, Time* t2) {
	Time total;

	total.min = (t1->min + t2->min) % 60;
	total.hour = t1->hour + t2->hour + (t1->min + t2->min) / 60;

	return total;
}
728x90

'c++ 기초' 카테고리의 다른 글

14) 함수 지시 포인터  (0) 2024.12.30
13) 재귀함수  (0) 2024.12.29
11) 조건문  (0) 2024.12.29
10) 반복문, 중첩 배열  (0) 2024.12.28
9) new 이용 동적 구조체  (0) 2024.12.28