如何做好网站的优化的监测评价,网页设计自我介绍模板代码html,深圳网站高端建设,钢铁网站模板C中编写没有参数和返回值的函数
返回值为 void
函数不需要将值返回给调用者。为了告诉编译器函数不返回值#xff0c;返回类型为 void。例如#xff1a;
#include iostream// void means the function does not return a value to the caller
void printHi()
{std…C中编写没有参数和返回值的函数
返回值为 void
函数不需要将值返回给调用者。为了告诉编译器函数不返回值返回类型为 void。例如
#include iostream// void means the function does not return a value to the caller
void printHi()
{std::cout Hi \n;// This function does not return a value so no return statement is needed
}int main()
{printHi(); // okay: function printHi() is called, no value is returnedreturn 0;
}在上面的例子中printHi 函数有一个有用的行为它打印“Hi”但它不需要返回任何东西给调用者。因此 printHi 被赋予了一个 void 返回类型。
当 main 调用 printHi 时执行 printHi 中的代码并打印“Hi”。在 printHi 结束时控制返回到 main 并且程序继续。
不返回值的函数称为无返回值函数或 void 函数。
void 函数不需要 return 语句
void 函数将在函数结束时自动返回给调用者。不需要 return 语句。
可以在 void 函数中使用 return 语句没有返回值——这样的语句将导致函数在执行return声明时返回给调用者。无论如何这与函数结束时发生的情况相同。因此在void函数的末尾放一个空的return语句是多余的。
#include iostream// void means the function does not return a value to the caller
void printHi()
{std::cout Hi \n;return; // tell compiler to return to the caller -- this is redundant since this will happen anyway!
} // function will return to caller hereint main()
{printHi();return 0;
}void 函数不能用于需要计算值的表达式
某些类型的表达式需要值。例如
#include iostreamint main()
{std::cout 5; // ok: 5 is a literal value that were sending to the console to be printedstd::cout ; // compile error: no value providedreturn 0;
}在上述程序中需要在 std::cout 的右侧提供要打印的值。如果没有提供值编译器将产生语法错误。由于对 std::cout 的第二次调用没有提供要打印的值这会导致错误。
现在考虑以下程序
#include iostream// void means the function does not return a value to the caller
void printHi()
{std::cout Hi \n;
}int main()
{printHi(); // okay: function printHi() is called, no value is returnedstd::cout printHi(); // compile errorreturn 0;
}第一次调用 printHi() 是在不需要值的上下文中调用的。由于函数不返回值这很好。
对函数 printHi() 的第二个函数调用甚至无法编译。函数 printHi 有一个 void 返回类型这意味着它不返回值。但是此语句试图将 printHi 的返回值发送到 std::cout 以进行打印。std::cout 不知道如何处理它会输出什么值。因此编译器会将其标记为错误。您需要注释掉这行代码才能使您的代码编译。
例子
如果将显示 Hello World 的工作委托给一个函数且该函数不做别的则它就不需要任何参数因为它除了显示 Hello World 外什么也不做也无需返回任何值因为您不指望这样的函数能提供在其他地方有用的东西。如下示例程序演示了一个这样的函数
#include iostream
using namespace std;void SayHello();int main()
{SayHello();return 0;
}void SayHello()
{cout Hello World endl;return; // an empty return
}输出
Hello World注意到第 3 行的函数原型将函数 SayHello()的返回类型声明为 void即不返回任何值。因此在第 1114 行的函数定义中 没有 return 语句。有些程序员喜欢在这种函数末尾包含一条空的 return 语句
void SayHello()
{cout Hello World endl;return; // an empty return
}该文章会更新欢迎大家批评指正。
推荐一个零声学院的C服务器开发课程个人觉得老师讲得不错 分享给大家LinuxNginxZeroMQMySQLRedis fastdfsMongoDBZK流媒体CDNP2PK8SDocker TCP/IP协程DPDK等技术内容 点击立即学习C/C后台高级服务器课程