I know void (*)(int)
is to function pointer but what is void(int)
?
It's used for std::function
template.
Say I have a function void fun(int){}
: decltype(&fun)
gives void(*)(int)
but decltype(fun)
gives void(int)
void: This method does not return anything. int: This method returns an integer.
The type void(int) is a function type, it's the type of a function taking one int and returning void . For example, it is the type of f if f is declared as void f(int); If T = void(int) , then T* is spelled void(*)(int) , so the latter is the type of a function pointer.
The short answer, is because the C++ standard requires main() to return int . As you probably know, the return value from the main() function is used by the runtime library as the exit code for the process. Both Unix and Win32 support the concept of a (small) integer returned from a process after it has finished.
int main represents that the function returns some integer even '0' at the end of the program execution. '0' represents the successful execution of a program. int main(void) represents that the function takes NO argument.
If T
is a type, then T*
denotes the type "pointer-to-T
".
The type void(int)
is a function type, it's the type of a function taking one int
and returning void
. For example, it is the type of f
if f
is declared as void f(int);
If T = void(int)
, then T*
is spelled void(*)(int)
, so the latter is the type of a function pointer. You can also form a reference to a function, which is T& = void(&)(int)
; this is occasionally more useful (e.g. you can take the address of a function lvalue).
Aside note: Function lvalues decay to their function pointer very easily. You can call a function either via a function lvalue or via a function pointer. When used as an operand for the indirection operator (*
), the function value decays, so you can dereference the pointer again and again:
printf("Hello world\n"); // OK
(*printf)("Hello world\n"); // also OK
(****printf)("Hello world\n"); // four-star programmer
Some of the only times that a function does not decay is when used as the operand of the address-of operator, or when bound to a reference:
void f(int); // our example function
void(*p1)(int) = &f; // no decay of "f" here
void(*p2)(int) = f; // "f" decays
void(&r1)(int) = f; // no decay of "f" here
void g(void(&callback)(int), int n) {
callback(n);
}
g(f, 10); // no decay of "f" here
template <typename F, typename ...Args>
decltype(auto) h(F&& callback, Args&&... args) {
return std::forward<F>(callback)(std::forward<Args>(args)...);
}
h(f, 10); // no decay of "f" here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With