Why is it that if I have a function like this, to swap two numbers, it doesn't work[swap], (I know I can do this by declaring pointers in the prototype, and then pass the address of the respective variables in main()), but works for array, without having to pass pointers and addresses.
Doesn't work
void num_exchange(int m, int n);
int main(){
int num1 = 5;
int num2 = 6;
num_exchange(num1 , num2 );
cout << "num1 =" << num1 << endl;
cout << "num2 =" << num2 << endl;
return 0;
}
void num_exchange(int m, int n){
int temp;
temp = m;
m = n;
n = temp;
}
Works
void arr_exchange(int [], int);
int main(){
int n[7] = { 0, 0, 0, 0, 0, 0, 0 };
arr_exchange(n, 7);
for (int i = 0; i < 7; i++)
cout << n[i] << " ";
return 0;
}
void arr_exchange(int x[], int){
for (int i = 0; i < 7; i++)
x[i] = 1;
}
void num_exchange(int m, int n){
int temp;
temp = m;
m = n;
n = temp;
}
modifies copies of the input integers. To make your code work use
void num_exchange(int& m, int& n){
int temp;
temp = m;
m = n;
n = temp;
}
instead (note the &
in the first line). This is called passing by reference. In general, use std::swap
to swap things.
void arr_exchange(int x[], int){
for (int i = 0; i < 7; i++)
x[i] = 1;
}
works because in C++
void arr_exchange(int x[], int){
is equivalent to
void arr_exchange(int* x, int){
So here a pointer is passed and thus the original data is modified.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With