int main(void)
{
int(*p)(const char*,...);
int printf(const char*,...);
when I do case:1 p=printf ---->suppose x
p("hello"); case 2: p=&printf;------>&x
p("hello");
while(!kbhit());
return 0;
}
in case 1 p is pointing to x
and in case 2 p is pointing to address of x
both cases are giving the same result why it is so?
a variable pointing to the two different location but gives the same result...why ?
@Disch
thanx for d reply..
I know how its working becoz both are pointing to the same location (giving the same address) .....but I don't know the reason why both are pointing to the same location while being two different variables.......
It's the same way as with arrays; using the name of a function in an expression where a reference to a function isn't expected causes the compiler to construct and return a pointer.
this:
1 2 3
int(*p)(constchar*, ...);
p=printf;
p=&printf;
follows the same logic as this:
1 2 3
int* p, a[10];
p = a;
p = &a[0];
somewhat useless trivia; in C, operator[] does not work with arrays and operator() does not work with functions - they are only defined for their respective pointers
#include <iostream>
void takes_array_ref(int (&)[3])
{
std::cout << "got array by reference\n";
}
void takes_a_pointer(int*)
{
std::cout << "got pointer\n";
}
void takes_func_ref(int (&)())
{
std::cout << "got function by reference\n";
}
void takes_func_ptr(int (*)())
{
std::cout << "got function pointer\n";
}
int main()
{
int a[3], f();
// the function takes_array_ref() expects a reference to array,
// so array is passed by reference
takes_array_ref(a);
// the function takes_a_pointer() can't accept a reference to array
// but can accept a pointer: the compiler constructs a pointer
// to the first element and passes that instead of the array
takes_a_pointer(a);
// same thing, done manually
takes_a_pointer(&a[0]);
// the function takes_func_ref() expects a reference to function
// so the function is passed by reference
takes_func_ref(f);
// the function takes_func_ptr() can't accept a reference to function
// but can accept a pointer: the compiler constructs a pointer
// to the function and passes that instead of the function itself
takes_func_ptr(f);
// same thing, done manually
takes_func_ptr(&f);
}
got array by reference
got pointer
got pointer
got function by reference
got function pointer
got function pointer
The original reason for both implicit conversions is that neither arrays not functions can be passed by value: they are not copyable in C. (C++ added the ability to pass them by reference, but in C there was simply no way to pass one to a function without building a pointer first, so it was automated)