Reputation: 1003
This code works fine after commenting statement one. Statement two gives some garbage value but at least it runs. I'm not getting how does the printf in argument gives a value if it's not called as a function?
#include<stdio.h>
int main()
{
int printf = 123; // statement one
printf ("%d", printf); // statement two
return 0;
}
Upvotes: 1
Views: 668
Reputation: 59607
In statement 2, when the identifier printf
is passed to the function, it is a function pointer - a pointer to the function printf
- and the garbage value is the result of trying to print this address using printf
and the format: %d
: you should see a compiler warning when printing a pointer using %d
.
Upvotes: 3
Reputation:
A function name without parentheses doesn't return a value - it evaluates to the address of the function (i. e. it is a function pointer of type size_t (*)(const char *, ...)
). Essentially, this is the address where the CPU will jump among the instructions whenever it encounters a call to printf()
.
By the way, if I recall correctly, assigning to a function's name is undefined behavior, so is printing a pointer using the %d
format specifier - you should use
printf("%p", (void *)printf);
Also, you can declare function pointers, assign them the address of another function and call them just fine:
size_t (*my_printf)(const char *, ...) = printf;
my_printf("This actually called printf!\n");
printf("my_printf: %p\n", (void *)my_printf);
printf("original printf: %p\n", (void *)printf);
The last two statements print the same address.
Edit: Strictly speaking, even the above "solution" is nonstandard as the Standard doesn't guarantee that function pointers can be cast to data pointer types. That means basically that there's no way for print the address of a function, however, on most systems, casting to void *
apparently works.
Upvotes: 4