Welcome to Software Development on Codidact!
Will you help us build our independent community of developers helping developers? We're small and trying to grow. We welcome questions about all aspects of software development, from design to code to QA and more. Got questions? Got answers? Got code you'd like someone to review? Please join us.
Comments on What does a variable followed by parentheses ("ptr()") mean?
Parent
What does a variable followed by parentheses ("ptr()") mean?
What does ptr()
mean in this code?
#include<stdio.h>
#include<stdlib.h>
void PrintHello()
{
printf("Hello\n");
}
int Add(int a, int b)
{
return a+b;
}
int main ()
{
void (*ptr)();
ptr = PrintHello;
ptr(); //For this specific line of code, what does it mean?
}
Post
void (*ptr)()
defines a function pointer. It says that ptr
is a pointer to a function. But that function must have a void
return type, and take an arbitrary number of parameters (that's what the empty parentheses defines).
Then, ptr = PrintHello
assigns the PrintHello
function to the ptr
pointer (and it works because PrintHello
matches the signature: it has a void
return type). So, now ptr
is pointing to PrintHello
.
Finally, ptr()
is calling the function that ptr
points to (in this case, PrintHello
). It has the same effect as calling PrintHello()
, and the parentheses are needed because it's a function call. But the function takes no parameters, thus the empty parentheses.
1 comment thread