
void f1(int& a) {
a = 1;
}
void f2(int* a) {
*a = 2;
}
void main() {
int x = 0;
f1(x);
std::cout << x << std::endl;
f2(&x);
std::cout << x << std::endl;
}
f1, f2가 결국 main함수의 x 데이터를 바꾸는 같은 동작을 하는데,
실제 둘의 차이는 뭘까요?

void f1(int& a) {
a = 1;
}
void f2(int* a) {
*a = 2;
}
void main() {
int x = 0;
f1(x);
std::cout << x << std::endl;
f2(&x);
std::cout << x << std::endl;
}
f1, f2가 결국 main함수의 x 데이터를 바꾸는 같은 동작을 하는데,
실제 둘의 차이는 뭘까요?
Translation: f1 and f2 end up changing the x data of the main function, doing the same thing, What's the real difference between the two?
For the simple case of a scalar such as int, the only practical difference is the need for the dereference operator (*) in f2.
If the argument is an array, using sizeof(a) in f1 would evaluate to the actual array size while in f2 it would evaluate to the size of a pointer. Even using sizeof(*a) in f2 will not return the array size.
If the argument is a class or struct, f1 must use the . operator to access a member while f2 must use the -> operator.
6 people are following this question.