#include<iostream>// void means the function does not return a value to the callervoidprintHi(){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 hereintmain(){printHi();return0;}
最佳实践
不要在不具有返回值的函数末尾添加 return 语句。
Void 函数不能被用在需要值的表达式
有些类型的表达式是需要一个值的,例如:
123456789
#include<iostream>intmain(){std::cout<<5;// ok: 5 is a literal value that we're sending to the console to be printedstd::cout<<;// compile error: no value providedreturn0;}
#include<iostream>// void means the function does not return a value to the callervoidprintHi(){std::cout<<"Hi"<<'\n';}intmain(){printHi();// okay: function printHi() is called, no value is returnedstd::cout<<printHi();// compile errorreturn0;}
#include<iostream>// Function that does not return a valuevoidreturnNothing(){}// Function that returns a valueintreturnFive(){return5;}intmain(){// When calling a function by itself, no value is requiredreturnNothing();// ok: we can call a function that does not return a valuereturnFive();// ok: we can call a function that returns a value, and ignore that return value// When calling a function in a context that requires a value (like std::cout)std::cout<<returnFive();// ok: we can call a function that returns a value, and the value will be usedstd::cout<<returnNothing();// compile error: we can't call a function that returns void in this contextreturn0;}
从 void 函数中返回值会导致编译报错
尝试在一个不具有返回值的函数中返回一个值会导致编译报错:
123456
voidprintHi()// This function is non-value returning{std::cout<<"In printHi()"<<'\n';return5;// compile error: we're trying to return a value}
#include<iostream>intprint()// note: return type of int{std::cout<<"A";return5;// the function will return to the caller herestd::cout<<"B";// this will never be printed}intmain(){std::cout<<print();// print() returns value 5, which will be print to the consolereturn0;}