알고리즘 문제풀이/C++

C++ - References and Pointers

aerimi-code 2026. 7. 31. 16:52

 

참조를 만들어주면 참조 값을 이용해서 변수값을 바꿀 수 있다. 

예를 들어, 함수에서 값을 변경할 때 참조 값을 전달해주면 변수값도 변경된다. 

 

void swap_num(int &i, int &j) {

  int temp = i;
  i = j;
  j = temp;

}

int main() {

  int a = 100;
  int b = 200;

  swap_num(a, b);

  std::cout << "A is " << a << "\n";
  std::cout << "B is " << b << "\n";

}

 

만약, 간단히 int i 와 int j 만 swap_num() 함수에 넣는다면, 

결과는 

A is 100
B is 200

 

 하지만 reference를 통해 pass 한다면
A is 200
B is 100

 

-궁금한 점 : C++에서는 포인터와 참조가 중요하다고 했는데, 다른 언어와 다른 점이 무엇인가?

 

 

Pass-By-Reference with Const

우리는 가끔 변수의 값 변경 방지를 위해 const 를 쓴다.

int triple(int const i) {

  return i * 3;

}

 

만약, 이 함수 안에서 i를 변경하면 compiler error가 발생한다.

 

참조 with const variable

int triple(int const &i) {

  return i * 3;

}

 

이것은 함수가 변경되지 않는것을 보장하면서, 

계산 비용을 줄여준다. (i 인수에 대한 복사를 만들지 않음)

 

 

Memory AddressA is 100

& symbol 은 reference 를 만들 때 사용하기도 하지만, 주소를 알려주기도 한다.

int porcupine_count = 3;
std::cout << &porcupine_count << "\n";

A is 100

output: 0x7ffd7caa5b54 

 

The double meaning of the & symbol can be tricky at first, so make sure to note:

  • When & is used in a declaration, it is a reference operator.
  • When & is not used in a declaration, it is an address operator.

 

Pointers

 

C++에서의 포인터는 중요함. 

 

자료 구조에서 배웠던 포인터 내용과 똑같음. 

&, * 사용해서 주소와 포인터가 가르키는 값 얻기

 

// Reference
int &reference = original;

// Pointer
int* pointer = &original;

 

ㅐㅕㅅB is 200ㅐㅕㅅ 


 

정리 

 

Q. What is the difference between a reference and a pointer?

A.   A reference is an alias for something else, while a pointer stores the memory address of something else.

Pointers are an older mechanism that was inherited from C, while references are a new mechanisms that originated in C++.