C++中的void函数返回详细介绍

2021年3月17日18:40:20 发表评论 1,902 次浏览

函数是"void"的, 因为它们不应该返回值。是的, 但不完全是。我们不能返回值, 但是肯定可以从void函数返回某些值。下面列出了一些情况。

void函数可以返回

我们可以简单地在void fun()中编写return语句。实际上, (为了代码的可读性)写返回值被认为是一种好习惯;表示功能结束的语句。

#include <iostream>
using namespace std;
  
void fun()
{
    cout << "Hello" ;
  
    // We can write return in void
    return ; 
}
  
int main()
{
    fun();
    return 0;
}

输出:

Hello

一个无效的fun()可以返回另一个无效函数

// C++ code to demonstrate void()
// returning void()
#include<iostream>
using namespace std;
  
// A sample void function
void work()
{
     cout << "The void function has returned "
             " a void() !!! \n" ;
}
  
// Driver void() returning void work()
void test()
{
     // Returning void function
     return work();
}
  
int main()
{
     // Calling void function
     test();
     return 0;
}

输出如下:

The void function has returned a void() !!!

上面的代码说明了void()实际上如何在不产生错误的情况下有效地返回void函数。

void()可以返回void值。

void()无法返回可以使用的值。但是它可以返回一个无效的值而不给出错误。

// C++ code to demonstrate void()
// returning a void value
#include<iostream>
using namespace std;
  
// Driver void() returning a void value
void test()
{
     cout << "Hello" ;  
   
     // Returning a void value
     return ( void ) "Doesn't Print" ;
}
int main()
{  
     test();
     return 0;
}

输出如下:

Hello

如果发现任何不正确的地方, 或者想分享有关上述主题的更多信息, 请写评论。

木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: