I was experimenting with pointers and created this example and I don’t understand why this doesn’t work. Could someone explain why the function does not perform the cin operations when I pass the values without referencing?
#included proper headers and stuff
...
int main()
{
int a, b;
swap(a,b);
cout << "A: " << a << endl;
cout << "B: " << b << endl;
return 0;
}
void swap(int * p1, int *p2)
{
cin >> *p1;
cin >> *p2;
int temp = *p1;
*p1 = *p2;
*p2 = temp;
}
Result
cin is skipped
A: 0
B: 0
Ugh. You’re passing integers where pointers are expected. The
swap()function is using the (random garbage) values in those uninitialized integers as machine addresses, and is writing data to those addresses. This doesn’t change the value in the integers you pass, of course — it changes some other random place in memory. Often this kind of program will crash with a segmentation violation; you’re just lucky (or unlucky).It would work if you passed pointers to the integers — i.e.,
swap(&a, &b)— but I think you understand that case already.