c++ - 为什么 void 返回一个值?

标签 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;
}

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

最佳答案

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

为了检查哪个函数已经重新调整,你必须将它分配给一些变量,就像这样

int a = swap(&a, &b);

但是这段代码有错误,因为交换函数没有返回任何东西。

另一个例子:

int func() {
    return 18;
}

int main() {
    int a =  func();
    cout << a;
}

没问题,因为变量 a 是 int 并且函数 func 返回一个 int。

关于c++ - 为什么 void 返回一个值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20030790/

相关文章:

C++ 改变排序方法

c++ - 如何在 QLayout 中查找给定类型的小部件?

c++ - 将控制字符传递给 char 数组

android - 是否可以用C++编写核心逻辑来开发浏览器、android和iphone?

c# - 在 Mono : invalid conversion of function? 中将 C++ 公开给 C#

java - 如何从 private int 返回 void?

C 中将 char 数组转换为 void * 指针

c# - C/C++/C#: Howto do "mount -a"

c - C 中的段错误(代码转储)错误

java - 返回 boolean 值而不是在 Java 中声明 void 类型?