Reputation: 14438
i tested this simple program of function pointer.
#include <stdio.h>
#include <conio.h>
void ptr();
void fun()
{
printf("fun() is called\n");
}
void ptr()
{
printf("ptr() is called\n");
}
int main()
{
void(*ptr)();
ptr=fun;
ptr(); // Why it works fine?
//(ptr)();
void(*a)()=fun;
(*a)();
_getch();
return 0;
}
output:
fun() is called
fun() is called
I have a question that why the function call statement ptr(); won't call user defined function ptr(), but calls fun() function? Why parentheses around ptr isn't necessary? What changes my program will require so my program displays output as following.
ptr() is called
fun() is called
Upvotes: 0
Views: 171
Reputation: 754700
It is an application of the usual scoping rules; local variables hide global variables of the same name.
Or, more accurately, variables defined in an inner scope hide variables of the same name in any outer scopes.
And scopes are basically controlled by sets of braces around blocks of statements (simplifying a bit).
You can get GCC to warn you about such problems with -Wshadow
.
The other part of the issue is that you can call functions via a pointer to function in (at least) two ways:
(*ptr_to_function)(); // Pre-standard notation
ptr_to_function(); // Notation allowed by standard C
So the call ptr();
is identical to (*ptr)();
in your program.
What changes does my program require to display:
ptr() is called fun() is called
The simplest change is to remove the line void (*ptr)() = fun;
.
You could also do something like:
#include <stdio.h>
void fun(void)
{
printf("fun() is called\n");
}
void ptr(void)
{
printf("ptr() is called\n");
}
int main(void)
{
void (*xyz)(void) = ptr;
void (*ptr)(void) = fun;
xyz();
ptr();
return 0;
}
Upvotes: 2
Reputation: 122483
When you define a local variable ptr
inside main
, it shadows the same name function ptr
which is global. So when you call ptr()
, it's the local function pointer ptr
that is called.
To make the function ptr
being called, you need to make sure the local variable ptr
is out of scope, as this artificial example:
int main()
{
{
void(*ptr)();
ptr=fun;
}
ptr();
}
Upvotes: 4