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;
}
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 toprintf().By the way, if I recall correctly, assigning to a function’s name is undefined behavior, so is printing a pointer using the
%dformat specifier – you should useAlso, you can declare function pointers, assign them the address of another function and call them just fine:
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.