请注意代码中我没有使用指针,但我有一些概念,如果我使用这个函数,当代码块完成时,该值将恢复正常.
但代码正在编译,实际上我会用指针得到答案.
我需要帮助,因为如果我有与指针相关的犯规概念,我会感到困惑.
void swap(int i, int j) {
int temp = i;
i = j;
j = temp;
}
int main() {
int a = 110;
int b = 786;
cout << "Before swapping the value" << endl;
cout << "'a' stores the value : " << a << endl;
cout << "'b' stores the value : " << b << endl;
swap(a,b);
cout << "\nAfter swapping the value" << endl;
cout << "'a' stores the value : " << a << endl;
cout << "'b' stores the value : " << b << endl;
swap(a, b);
cout << "\nAnd back again swapping the value" << endl;
cout << "'a' stores the value : " << a << endl;
cout << "'b' stores the value : " << b << endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
您的swap函数不会交换范围内的值main,因为i并且j是函数局部变量.为了获得您期望的行为,您应该通过引用传递.
void swap(int& i, int& j) {
int temp = i;
i = j;
j = temp;
}
Run Code Online (Sandbox Code Playgroud)
您的代码实际上不会交换值.
猜猜:
我认为你是using namespace std;来自#include你正在与之碰撞的标准库中的一个std::swap.我认为std::在你的情况下调用函数的版本,这是你的代码看起来"工作"的唯一原因.