为什么void返回一个值?

Sil*_*con 5 c++ void

我无法理解一件奇怪的事情.这是我的计划:

#include <iostream>
using namespace std;

void Swap(int *a , int *b)
{
    int temp;
    temp = *a;
    *a = *b;
    *b = temp;
}

int main()
{
    int a=0;
    int b=0;

    cout<<"Please enter integer A: ";
    cin>>a;

    cout<<"Please enter integer B: ";
    cin>>b;

    cout<<endl;

    cout<<"************Before Swap************\n";
    cout<<"Value of A ="<<a<<endl;
    cout<<"Value of B ="<<b<<endl;

    Swap (&a , &b);

    cout<<endl;

    cout<<"************After Swap*************\n";
    cout<<"Value of A ="<<a<<endl;
    cout<<"Value of B ="<<b<<endl;

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

现在,如果你看一下"Swap"这个函数,我就用了"void Swap".因此它不能向main函数返回任何值(只有"int"返回一个值(至少这是我老师教给我的)).但是如果你执行它,值将在主函数中交换!怎么会 ?有谁能告诉我它是如何可能的?

Dim*_*ima 6

您的示例中的交换函数只交换两个整数,但不返回任何内容.

为了检查已重新调整的函数,必须将其分配给某个变量,如下所示

int a = swap(&a, &b);
Run Code Online (Sandbox Code Playgroud)

但这段代码有错误,因为交换函数不返回任何内容.

另一个例子:

int func() {
    return 18;
}

int main() {
    int a =  func();
    cout << a;
}
Run Code Online (Sandbox Code Playgroud)

没问题,因为变量a是int而函数func返回一个int.


小智 1

实际上,该函数没有返回值。它只是通过变量的地址访问值并从它们的引用中交换它们。你的代码是正确的,现在我已经澄清了你的概念,没有任何长解释。就这样。