C++ 반환형 int& 와 int의 차이점이 무엇인가요??

sungsoo1214의 이미지

int increment(int& n);
int main()
{
int num=0;
cout<<"num= "< return 0;
}

int increment(int& n)
{
++n;
return n;
}

다음에서 increment 함수부분에 반환형을 int -> int&로 했을 때에 어떤 차이가 있나요??
결과는 같게 나오는데 차이를 모르겠습니다.

sungsoo1214의 이미지

int increment(int& n);
int main()
{
	int num=0;
	cout<<"num= "<<increment(num)<<endl;
	return 0;
}
 
int increment(int& n)
{
	++n;
	return n;
}
 

increment 함수에서 반환형을 int 대신에 int&로 하면 어떤 차이가 있는지 모르겠습니다. 결과는 똑같이 나오는데 차이점을 모르겠네요..
익명 사용자의 이미지

#include "stdafx.h"
#include

using namespace std;

int increment(int& n);
int increment2(int n);
int& increment3(int& n);

int _tmain(int argc, _TCHAR* argv[])
{
int num=0;
cout << "num= " << increment(num) << endl;
cout << num << endl;
cout << "num= " << increment2(num) << endl;
cout << num << endl;
cout << "num= " << increment3(num) << endl;
cout << num << endl;

getchar();
return 0;
}

int increment(int& n)
{
++n;
return n;
}

int increment2(int n)
{
++n;
return n;
}

int& increment3(int& n)
{
++n;
return n;
}

위 코드를 실행해보시면 감이 오실겁니다.
&는 레퍼런스라서 주소값을 넘기고 int는 걍 값을 넘기는 거구요.
call by value, call by reference. 찾아보시면 도움이 될듯 합니다 ;)

gorillia의 이미지

&는 레퍼런스라서 주소값을 넘긴다는 표현보다는..
별칭을 주어준다라고 말해주는게 좋을것같아요

다르게 설명해보자면 main의 num을
increment내에서 n이라는 별칭을가진놈으로 사용하겠다고 선언하고
전위 증가연산자를 통해 값을 늘리고
그 값을 새로 int형으로 반환합니다.
그대로 반환하지 않고 그값을 수정하여 return n+1;으로 반환할수도 있습니다.
"increment의 반환형 int"로 반환하는거니까요

하지만 increment3는
n이라는 별칭을가진놈으로 사용하겠다고 선언하고
전위 증가연산자를 통해 값을 늘린것까진 같지만
반환을 int가 아니라 int의 별칭을 가진놈을 반환해야하므로
return n+1; 이런식으로 반환할수 없습니다.

int 함수내에서 return n;은 n의 '값'을 반환하겠다는 뜻이지만
int& 함수내에서 return n;은 n이라는 별칭을 가진 '변수'를 반환하겠다는 뜻이고
int& 함수내에서 n+1는 n의값에 1을 더한 '값'이 되어버리기때문입니다.

여기까지는 질문하신것을 그대로 설명해드렸는데
처음부터 드리고싶었던말은
레퍼런스를 사용하실꺼면 그냥

int increment(int& n);
int main()
{
int num=0;
increment(num);
cout<<"num= "<< num << return 0;
}

void increment(int& n)
{
++n;
}

이렇게 쓰실수도 있습니다

댓글 달기

Filtered HTML

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

BBCode

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param>
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

Textile

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • You can use Textile markup to format text.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Markdown

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • Quick Tips:
    • Two or more spaces at a line's end = Line break
    • Double returns = Paragraph
    • *Single asterisks* or _single underscores_ = Emphasis
    • **Double** or __double__ = Strong
    • This is [a link](http://the.link.example.com "The optional title text")
    For complete details on the Markdown syntax, see the Markdown documentation and Markdown Extra documentation for tables, footnotes, and more.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Plain text

  • HTML 태그를 사용할 수 없습니다.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 줄과 단락은 자동으로 분리됩니다.
댓글 첨부 파일
이 댓글에 이미지나 파일을 업로드 합니다.
파일 크기는 8 MB보다 작아야 합니다.
허용할 파일 형식: txt pdf doc xls gif jpg jpeg mp3 png rar zip.
CAPTCHA
이것은 자동으로 스팸을 올리는 것을 막기 위해서 제공됩니다.