본문 바로가기
[C++]

C++ 레퍼런스 (&) 분석

by Hevton 2023. 8. 30.
반응형

 

코테를 준비하면서 한가지 궁금한 점이 생겨서 메모

#include <iostream>
#include <stack>

using namespace std;

int main() {
    
    
    stack<pair<int, int>> s;
    
    s.push({10, 10});
    
    
    pair<int, int> top = s.top();
    
    top.second -= 10;
    
    cout << s.top().second << "\n";
    
    
}

출력 : 10

 

#include <iostream>
#include <stack>

using namespace std;

int main() {
    
    
    stack<pair<int, int>> s;
    
    s.push({10, 10});
    
    
    pair<int, int>& top = s.top();
    
    top.second -= 10;
    
    cout << s.top().second << "\n";
    
    
}

출력 : 0

 

위 아래 두 코드의 차이점은 단 한 줄

pair<int, int> top = s.top();

이거냐

pair<int, int>& top = s.top();

이거냐이다.

 

&를 사용하면 레퍼럴이 되어서, 변화가 실제 값에도 영향을 끼친다.

반응형