c++ - 为什么在此代码中当 "swap"函数写在 int main() 之后而不是之前时会发生交换?

标签 c++ call-by-value

所以我的疑问是, 我正在尝试按值(value)调用, 在运行给定代码时,当我在 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> ,您无法保证哪些标准 header 最终会根据实现的构造方式包括其他标准 header 。

关于c++ - 为什么在此代码中当 "swap"函数写在 int main() 之后而不是之前时会发生交换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58313411/

相关文章:

c++ - 如何将字符串文字传递给用 C++ 处理的函数?

c++ - Direct3D9 游戏 : Spaceship camera

c++ - 非指针类成员 : how good is it?

c++ - 捕获函数参数中的常量表达式

c++ - 构造以特定前缀开头的特定长度的字符串

c - 如何理解指针 (*) 和寻址 (&) 运算符的概念?

c++ - 按值|引用调用的另一个问题

abap - EXPORTING方法参数如何按值传递?

c++ - gdb 不会执行二进制操作