Home >Backend Development >C++ >How to use void in c++

How to use void in c++

下次还敢
下次还敢Original
2024-05-06 18:00:24820browse

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>

2. Declare a function pointer or reference:

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

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>
  • 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>

    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>

    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!

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