tags:

views:

114

answers:

4
int main()
{
  int main=5;
  printf("%d",main);
  return 0;
}

In this case there is no error and the gcc compiler prints 5. But if I write

 int main()
    {
        int printf=5;
        printf("%d",printf);
        return 0;
    }

the compiler shows an error..why ?

+1  A: 

You shouldn't use function names as variable names, ever, for any reason.

Alexander Rafferty
This is not an answer.
sje397
It is to the title question.
Alexander Rafferty
"Yes, but you shouldn't" would be an answer. What you have there is just advice. (BTW, I didn't DV)
sje397
Bloody good advice though. I boggled when I saw the question. I think this answer is more useful to the OP than the actual answer.
Blank Xavier
It's very difficult advice to follow, since if you include headers from third parties, you don't necessarily know all the names of all the functions that are (or ever will be) declared in that header. C development relies on programmers using naming conventions, but it doesn't rely on them so strongly that it breaks if you unwittingly shadow a name (since if it's unwitting, you won't also use the name to reference the function, as Parixit does in the example code, because you don't realise it's a function). You could have problems if the header uses the function name in macros, though.
Steve Jessop
+2  A: 

In your first code snippet, you declare a local variable main, which is in the local scope, so it has no effect on the global scope (where the main() function is declared)

In the second code snippet, you declare "printf" in global scope, where the printf() function lives, so you have a conflict.

Philippe Leybaert
Downvoted? No reason?? Thank you.
Philippe Leybaert
It wasn't me that downvoted you, but on the assumption the printf lines should be inside main, your explanation is wrong. The error occurs because he is trying to treat an int named printf (which shadows the function declaration) as a function.
JeremyP
+2  A: 

In the second example, you have declared a local variable of type 'int' called 'printf'. This will take precedence over the global function of the same name. So the error is that the name 'printf' refers to an int, not a function.

In your first example, you override the global function name 'main' with a local variable called 'main'. If you had not done that, you would in fact be able to call the 'main' function from within the main function, and that would have worked. With your variable declaration, that is no longer possible as the local variable declaration takes precedence - but it's still perfectly usable in the variable form.

sje397
+9  A: 

In your 1st example you "hide" the main function, replacing it with an int object.

In your 2nd example you "hide" the printf function, replacing it with an int object. Trying to call an int is illegal.

5("foo"); /* illegal to call "function" 5 */
pmg