Home  >  Article  >  Backend Development  >  How does a C++ function return void type?

How does a C++ function return void type?

WBOY
WBOYOriginal
2024-04-20 13:06:011132browse

The void function in C does not return any value, and its syntax is void function_name(). Common uses include: Entering user input, such as getting the user's age and printing it to the console.

C++ 函数如何返回 void 类型?

The return type of void function in C

In C, the void type is a special The return type means that the function does not return any value. This is different from other functions, which usually return a specific type of value, such as an integer, string, or object.

The syntax of the void function is as follows:

void function_name();

The following is an example of a simple function that returns the void type:

void print_hello() {
  std::cout << "Hello, world!" << std::endl;
}

You can use it by calling the function void function:

print_hello();

Calling a void function does not generate any return value, so you cannot assign the return value to a variable or use it as input to another expression.

Practical case: Entering the user’s age

A common use of the void function is to enter user input. Here is an example of a C program that uses the void function to get the age from the user and print it to the console:

#include <iostream>

void get_age() {
  int age;
  std::cout << "Enter your age: ";
  std::cin >> age;
  std::cout << "Your age is: " << age << std::endl;
}

int main() {
  get_age();
  return 0;
}

In the above example, get_age() The function uses void as the return type since it does not return any value. get_age() The function reads the age from the user and prints it to the console. main() The function calls the get_age() function to allow the user to enter their age and print it to the console.

The above is the detailed content of How does a C++ function return void type?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn