为什么在此代码中当 "swap" 函数写在 int main() 之后而不是之前时会发生交换?
why in this code swapping happens when the "swap" function is written after int main() but not before it?
所以我的疑问是,
我正在尝试按价值呼叫,
虽然 运行 给定的代码,但当我在 int main() 之后编写函数定义时会发生交换
但是,如果我将函数定义剪切并粘贴到 int main() 上方,则交换不会发生。这是为什么?
#include<iostream>
#include<string>
#include<vector>
#include<bitset>
#include<fstream>
using namespace std;
#define ADDU 1
#define SUBU 3
#define AND 4
#define OR 5
#define NOR 7
#define MemSize 65536
void swap(int a, int b)
{
int temp = a;
a = b;
b = temp;
}
int main(){
// int a = 20;
// int *p = &a;
// cout<<"P: "<<p<<endl<<"*P gives: "<<*p<<endl<<"&p gives: "<<&p<<endl<<"&a : "<<&a;;
int x,y;
x = 10;
y = 20;
cout<<"Before Swapping: "<<"x: "<<x<<endl<<"y: "<<y<<endl;
swap(x,y);
cout<<"After Swapping: "<<"x: "<<x<<endl<<"y: "<<y<<endl;
}
你的交换函数实际上并没有交换任何东西,因为它通过值而不是引用来获取参数。您所做的只是操纵该函数的局部变量。
当你在之后 main
才引入它时,你调用它时它不在范围内,所以用std::swap
代替。 std::swap
工作正常。
虽然您没有具体说明 std::swap
,但您写的 using namespace std;
删除了该要求(有充分理由不这样做!!)。而且,尽管您没有 #include <algorithm>
,但您不能保证哪个标准 headers 最终会根据实现的构建方式包括其他标准。
所以我的疑问是, 我正在尝试按价值呼叫, 虽然 运行 给定的代码,但当我在 int main() 之后编写函数定义时会发生交换 但是,如果我将函数定义剪切并粘贴到 int main() 上方,则交换不会发生。这是为什么?
#include<iostream>
#include<string>
#include<vector>
#include<bitset>
#include<fstream>
using namespace std;
#define ADDU 1
#define SUBU 3
#define AND 4
#define OR 5
#define NOR 7
#define MemSize 65536
void swap(int a, int b)
{
int temp = a;
a = b;
b = temp;
}
int main(){
// int a = 20;
// int *p = &a;
// cout<<"P: "<<p<<endl<<"*P gives: "<<*p<<endl<<"&p gives: "<<&p<<endl<<"&a : "<<&a;;
int x,y;
x = 10;
y = 20;
cout<<"Before Swapping: "<<"x: "<<x<<endl<<"y: "<<y<<endl;
swap(x,y);
cout<<"After Swapping: "<<"x: "<<x<<endl<<"y: "<<y<<endl;
}
你的交换函数实际上并没有交换任何东西,因为它通过值而不是引用来获取参数。您所做的只是操纵该函数的局部变量。
当你在之后 main
才引入它时,你调用它时它不在范围内,所以用std::swap
代替。 std::swap
工作正常。
虽然您没有具体说明 std::swap
,但您写的 using namespace std;
删除了该要求(有充分理由不这样做!!)。而且,尽管您没有 #include <algorithm>
,但您不能保证哪个标准 headers 最终会根据实现的构建方式包括其他标准。