새소식

🏫 School/[23-2] 객체지향프로그래밍

[C++] 함수에 대한 기본 설명 (1)

  • -

함수를 이해하기 위한 용어

[Declare]

- 함수의 이름과 그 type을 소개

// declare 부분
int iSqrt(int );

 

[Define]

- 함수의 이름/type과 body 부분을 모두 포함

// define 부분
int iSqrt(int p) {
	return p*p
}

[Call]

- 이전에 define 되어있던 함수를 사용하는 단계
- 일반적으로 main 함수나 다른 함수 내에 존재

// call 부분
y = iSqrt(x);

[Return Value = Result]

- 함수의 결과값을 의미 => 즉 함수를 빠져나오면서 들고 나오는 값
- 함수의 type이 주로 return value의 type

기본적인 함수와 libraries

- 어떤 함수가 포함된 library를 include하면, 굳이 declare이나 define 과정 필요 없음

[cmath library]

- c++에서의 수학적 함수들이 모여있음
- 자주쓰는 sqrt함수도 해당 라이브러리에 포함

cmath 라이브러리 내의 함수들

[C libraries]

 

[Container libraries]

[Standard I/O libraries]

 

함수

[함수의 구조]

 

[Input & Output이 없는 함수]

- 일반적으로 input과 output이 모두 없다면, void type 의 함수를 생성함
- caller가 제공해야 하는 값은 있을수도 있고 없을 수도 있음
- 일반적으로 program의 연산 보다는 행위를 요구 하는 것들이 많음 (ex. 화면에 ~를 띄워라!)

// 예시 코드
#include <iostream>
using namespace std;

// prompt 함수는 (caller 제공 value) input, output 모두 존재 X
void prompt () {
	cout << "Please enter an integer value: ";
}

int main () {
	int value1, value2, sum;
    cout<<"This program adds together two integers.\n";
    prompt(); //함수 call
    cin>>value1;
    prompt(); //함수 call
    cin>>value2;
    sum = value1+value2;
    cout<<value1<< " + "<<value2<<" = "<<sum<<'\n';
}

[Return 값이 있는 함수]

- Return 값이 존재하는 함수의 경우에는 return value의 type에 맞게 함수의 type을 결정

// 예시 코드
#include <iostream>
using namespace std;

// prompt 함수는 (caller 제공 value) input 존재 X, (return) output은 존재
int prompt () {
	int result;
	cout << "Please enter an integer value: ";
    cin >> result;
    return result;
}

int main () {
	int value1, value2, sum;
    cout<<"This program adds together two integers.\n";
    value1 = prompt(); // 함수 call
    value2 = prompt(); //함수 call
    sum = value1+value2;
    cout<<value1<< " + "<<value2<<" = "<<sum<<'\n';
}

[Input & Return 값이 있는 함수]

- input과 return 값이 모두 있는 함수는 call할때 꼭 value값을 전달해야 함

// 예시 코드
#include <iostream>
using namespace std;

// prompt 함수는 (caller 제공 value) input과 (return) output 모두 존재
int prompt (int n) {
	int result;
	cout << "Please enter an integer # "<<n<<" : ";
    cin >> result;
    return result;
}

int main () {
	int value1, value2, sum;
    cout<<"This program adds together two integers.\n";
    value1 = prompt(1); // 함수 call
    value2 = prompt(2); //함수 call
    sum = value1+value2;
    cout<<value1<< " + "<<value2<<" = "<<sum<<'\n';
}

[Default Arguments]

- 함수를 call 할 때, value를 제공하지 않으면 알아서 채워 넣는 값
- input이 있어야 하는 함수에서 사용

// 예시 코드
#include <iostream>
using namespace std;

void point(int x=3, int y=4) {
	cout << "x = " << x << ",y = " << y << endl;
}

int main() {
	point(1, 2);	// x = 1, y = 2
    point(1);		// x = 1, y = 4
    point();		// x = 3, y = 4
}
Contents

포스팅 주소를 복사했습니다

이 글이 도움이 되었다면 공감 부탁드립니다.