Home > Backend Development > C++ > body text

How to use void in c++

下次还敢
Release: 2024-05-06 18:00:24
Original
740 people have browsed it

The void keyword in C is used to specify that a function does not return any value. Its usage includes: defining a function without a return value, declaring a function pointer or reference as a placeholder or default value type inference

How to use void in c++

Usage of void in C

void is a keyword in C, used to specify that the function has no return value. It is used in the following situations:

1. Define a function without a return value:

<code class="cpp">void print_message() {
  std::cout << "Hello World!" << std::endl;
}</code>
Copy after login

2. Declare a function pointer or reference:

<code class="cpp">void (*callback)(int); // 指向接收int参数并无返回值的函数的指针
void& func_ref = my_function; // 引用到无返回值函数</code>
Copy after login

3. As a placeholder or default value:

In some cases, void can be used as a placeholder or default value. For example:

  • In a macro definition, void can indicate that no code is generated when the macro is expanded:

    <code class="cpp">#define MY_MACRO(x) x
    #define EMPTY_MACRO() void</code>
    Copy after login
  • In template metaprogramming, void Can indicate that the type or value does not exist:

    <code class="cpp">template<typename T>
    void foo() {
    static_assert(std::is_same<T, void>::value, "T must be void");
    }</code>
    Copy after login

    4. Type inference:

    In C 14 and later, void can be used For type inference, it means that the function returns an untyped expression:

    <code class="cpp">auto result = []() { return 42; }(); // result类型为int</code>
    Copy after login

    Note:

    • void is not a type, so you cannot use void to declare a variable or object.
    • The void function cannot explicitly return any value (including void).
    • The void function can use the return statement to end the execution of the function.

    The above is the detailed content of How to use void in c++. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
c++
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!