본문 바로가기
C++/C++ 기초 문법

[C++] 함수

by 후야- 2023. 12. 26.

📙 함수

-> 함수는 프로그램의 가독성을 높이기 위해 사용한다.

#include <iostream>
#include <format>

using namespace std;

void testFunction(int i, char c)
{
	cout << format("{}", i) << endl;
	cout << format("{}", c) << endl;
}


int main()
{
	testFunction(5, 'a');
	testFunction(10, 'd');
	testFunction(1, 'g');
	

	return 0;
}

-> C++ 에서는 함수의 매개변수 리스트 자리에 void 대신 그냥 비워두면 된다. 하지만 리턴값이 없다는 것을 표시할 때는 C언어와 마찬가지로 리턴 타입 자리에 void 를 적어줘야 한다.


◾ 함수는 호출한 측으로 값을 리턴할 수 있다.

#include <iostream>
#include <format>

using namespace std;

int testFunction(int test1, int test2)
{
	return test1 + test2;
}


int main()
{
	int sum{ testFunction(5, 10) };
	cout << format("두 값의 덧셈: {}", sum) << endl;
	
	return 0;
}

◾ 함수 리턴 타입 추론

-> 함수의 리턴 타입을 컴파일러가 알아서 지정할 수 있다. 리턴 타입 자리에 auto 키워드만 적으면 된다.

auto testFunction(int test1, int test2)
{
	return test1 + test2;
}

◾ 현재 함수 이름

모든 함수는 내부적으로 __func__ 라는 로컬 변수가 정의되어 있는데 이 변수의 값은 현재 함수의 이름이며, 주로 로그를 남기는 데 활용한다.

auto testFunction(int test1, int test2)
{
	cout << "Entering function " << __func__ << endl;
	return test1 + test2;
}

 


◾ 함수 오버로딩

-> 이름은 같지만 매개변수 구성은 다른 함수를 여러 개 제공한다는 뜻이다

-> 리턴 타입만 달라서는 안 되며, 매개변수의 타입이나 개수도 달라야 한다.

#include <iostream>
#include <format>

using namespace std;

int testGO(int a, int b) { return a + b; }
double testGo(double a, double b) { return a + b; }

int main()
{
	cout << testGo(3, 5) << endl;
	cout << testGo(1.22, 3.44) << endl;
	return 0;
}

 

✔ 컴파일러는 주어진 인수를 기반으로 두 가지 오버로딩된 함수 중에서 적합한 버전을 선택해서 출력한다.