Reputation: 795
This is the declaration of a variable printf:
int printf=90;
This runs without any error , but if I try to print the value of the identifier with the given name printf , then it gives error , so why is it that although the compiler is allowing printf to be used as an identifier but we can't later print its value .
Upvotes: 4
Views: 121
Reputation: 399863
Your question is a bit mixed up.
C has "scope rules", that govern how a name (like printf
) is resolved from a given point in the code. It's possible, and legal according to the scope rules, to shadow a name from an outer scope.
Typically printf
is extern
-declared from <stdio.h>
, and its value is replaced by the proper function address from the standard library by the linker.
But if you declare a new variable like that, you are shadowing the name. Basically you get a new variable of a new type, with the same name as an existing one. The outer, original, printf
then becomes unreachable from that scope, since C doesn't have a scope resolution operator. In C++, you could use ::printf
which always references the global printf
. C doesn't have that.
You can work around it by copying the original value of printf
before shadowing it:
{
int (*theprintf)(const char *fmt, ...) = printf;
int printf = 90;
theprintf("now printf has the value %d\n", printf);
}
As mentioned in a comment, once you're done with your local variant you can re-declare it as extern
to get it back, but you can't do that in the same scope:
{
extern int printf(const char * fmt, ...);
printf("hello?\n");
}
Upvotes: 6