C++

C++ return문 총정리

김구티2 2024. 3. 17. 16:40

1. return문의 개념

return 문은 실행의 흐름을 호출된 곳에서 함수로 반환한다. 이 문은 조건문을 반드시 필요로 하지는 않는다. 문이 실행되자마자 프로그램의 흐름은 즉시 중지되고, 호출된 곳에서 컨트롤을 반환한다. return문은 void 함수에 대해서는 반환할 수도 있고 반환하지 않을 수도 있지만, non-void 함수에 대해서는 반환 값을 반환해야 한다.

 

구문:

return[expression];

 

return문을 사용하는 방법은 매우 다양하다. 그 방법들에 대해 알아보도록 한다.

2. 값을 반환하지 않는 메서드

C++에서 메서드가 반환 유형일 때 반환문을 건너뛸 수 없다. 반환문은 void 유형에 대해서만 건너뛸 수 있다. 함수가 아무것도 반환하지 않는 경우, void return 유형이 사용된다. 따라서 함수 정의에 void return 유형이 있으면, 함수 내부에는 반환 문이 일반적으로는 없다.

 

구문:

void func()
{
    .
    .
    .
}

 

예시:

// C++ code to show not using return 
// statement in void return type function 
#include <iostream> 
using namespace std; 

// void method 
void Print() 

     cout << "Welcome to Gutilog"


// Driver method 
int main() 


     // Calling print 
     Print(); 

     return 0; 

 

출력:

Welcome to Gutilog

 

그렇다면 이제 void return type 함수 안에 return 문이 있으면 어떨까 하는 의문이 생긴다. 함수 정의에 void return type이 있으면 그 함수 안에는 return 문이 없다. 그러나 그 안에 return 문이 있으,면 그 함수의 구문이 다음과 같이 되어도 문제가 없게 된다.

 

구문:

void func()
{
    return;
}

 

이 구문은 함수에서 함수의 흐름을 끊고 함수에서 뛰어내리기 위해 마치 점프문처럼 사용된다. 그렇기에 함수에서 사용하는 break문의 대안이라고 생각할 수 있다.

 

예시:

// C++ code to show using return 
// statement in void return type function 
#include <iostream> 
using namespace std; 

// void method 
void Print() 

     cout << "Welcome to Gutiworld"

     // void method using the return statement 
     return


// Driver method 
int main() 


     // Calling print 
     Print(); 
     return 0; 

 

출력:

Welcome to Gutiworld

 

그런데 반환문이 void return type 함수에서 값을 반환하려고 하면, 오류가 발생하게 된다.

 

잘못된 구문:

void func()
{
    return value;
}

 

예시:

// C++ code to show using return statement 
// with a value in void return type function 
#include <iostream> 
using namespace std; 

// void method 
void Print() 

     cout << "Welcome to Gutisesang"

     // void method using the return 
     // statement to return a value 
     return 10; 


// Driver method 
int main() 


     // Calling print 
     Print(); 

     return 0; 

 

출력:

warning: 'return' with a value, in function returning void

3. 값을 반환하는 메서드

return type을 정의하는 메서드의 경우, return문 뒤에 해당 지정된 return type의 return 값이 바로 이어져야 한다.

 

구문:

return-type func()
{
    return value;
}

 

예시:

// C++ code to illustrate Methods returning 
// a value using return statement 
#include <iostream> 
using namespace std; 

// non-void return type 
// function to calculate sum 
int SUM(int a, int b) 

     int s1 = a + b; 

     // method using the return 
     // statement to return a value 
     return s1; 


// Driver method 
int main() 

     int num1 = 10; 
     int num2 = 10; 
     int sum_of = SUM(num1, num2); 
     cout << "The sum is " << sum_of; 
     return 0; 
}

 

출력:

The sum is 20

 

참고로, 반환문을 사용하여 함수에서 단일 값만 반환할 수 있다. 만일 여러 값을 반환하길 원한다면, 포인터, 구조, 클래스 등을 사용하는 방법이 있을 것이다.

 

728x90