Parikshita
Parikshita

Reputation: 1327

Can we use main, printf,scanf for naming identifiers?

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 ?

Upvotes: 4

Views: 745

Answers (4)

pmg
pmg

Reputation: 108978

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 */

Upvotes: 9

sje397
sje397

Reputation: 41852

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.

Upvotes: 2

Philippe Leybaert
Philippe Leybaert

Reputation: 171864

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.

Upvotes: 2

Alexander Rafferty
Alexander Rafferty

Reputation: 6233

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

Upvotes: 1

Related Questions