Home >Backend Development >C++ >How to use void in c++
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
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:
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!