在编程语言中,函数被用于使代码模块化。在许多应用程序中,我们创建子模块来使我们的代码易于编写、易于调试,并通过反复拒绝不必要的代码来进行优化。为了实现这些功能,函数出现在画面中。在许多情况下,函数接受参数并返回某些东西。有时它可能不接受任何参数,但返回某些东西。还有一些特殊情况,函数既不接受任何参数,也不返回任何东西。在本教程中,我们将介绍C++中不带参数和返回值的这种函数。
要定义一个没有参数和返回类型的函数,返回类型必须是void,参数列表可以是空的,或者我们可以在那里写void。语法如下所示。
void function_name ( ) { // function body }
void function_name ( void ) { // function body }
In such a scenario, where we just print something, or performing any display-like operations, or perform some task whole inside the function, such cases are suitable for this type of function. Let us see a such case and let us see the implementation in C++. In our first example, we will print a star pyramid for fixed 10 lines.
#include <iostream> #include <sstream> using namespace std; void pyramid( ) { for( int i = 1; i <= 10; i++ ) { for( int j = 1; j <= 10 - i; j++ ) { cout << " "; } for( int j = 1; j <= i; j++ ) { cout << "* "; } cout << endl; } } int main() { pyramid(); }
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
This program, it is printing the pyramid for 10 sizes only. As the size is fixed, it does not take any parameter, and since it is printing the asterisks directly, nothing is returned. Let us see another example for the similar star pyramid with taking inputs from the user, but there also we do not pass any argument and the function will not return anything.
#include <iostream> #include <sstream> using namespace std; void pyramid( void ) { int n; cout << "Enter line numbers: "; cin >> n; for( int i = 1; i <= n; i++ ) { for( int j = 1; j <= n - i; j++ ) { cout << " "; } for( int j = 1; j <= i; j++ ) { cout << "* "; } cout << endl; } } int main() { pyramid(); }
Enter line numbers: 18 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
Here we are taking input from the user using the cin method. No extra argument passing is required for this solution.
函数用于使代码模块化和易于处理。在大多数情况下,我们使用函数来接受参数,并在某些计算后返回某个值。但这不是强制性的过程。在本文中,我们讨论了如何在C++中编写一个不接受任何参数并且不返回任何内容的函数。当某个任务是预定义的时候,我们可以使用这种类型的函数。就像在我们的第一个示例中,星星金字塔只有10行,所以不需要额外的输入。在第二个示例中,我们将行号作为输入,但不作为输入参数。我们直接从用户那里获取输入,并将其存储在此函数内的一个局部变量中,然后在循环中使用它。