Jeegar Patel
Jeegar Patel

Reputation: 27230

Are main and fopen valid variable names?

The C standard says variable names should not match with standard C keywords and standard function names. Then why does the code below compile with no errors?

#include <stdio.h>

int main()
{
    int main = 10;
    printf("Magic is %d", main);
    return 0;
}

See also http://codepad.org/OXk4lZZE

In an answer below, ouah writes

main is not a reserved identifier and it is allowed to name variables as main in C

so considering the program below, does that mean that fopen is likewise not reserved?

#include <stdio.h>

int main()
{
    int fopen = 10;
    printf("Magic is %d", fopen);
    return 0;
}

Upvotes: 13

Views: 4440

Answers (2)

TryinHard
TryinHard

Reputation: 4118

By default the global variables and the functions are extern in nature where as in block scope they are auto by default.

To check how the linker resolves the symbols check here

Upvotes: 1

ouah
ouah

Reputation: 145899

You program is a valid C program.

main is not a reserved identifier and it is allowed to name variables as main in C.

What you cannot do is name a variable main at file scope but this is the same as with other variables that would conflict with a function of the same name:

This is not valid:

int main = 0;

int main(void)
{
}

For the same reasons this is not valid:

int foo = 0;

int foo(void)
{
    return 0;
}

EDIT: to address the OP question edit, the second program in OP question is also valid as C says

(C11, 7.1.3p1) "All identifiers with external linkage in any of the following subclauses (including the future library directions) and errno are always reserved for use as identifiers with external linkage."

but the fopen variable identifier has block scope and none linkage in the example program.

Upvotes: 32

Related Questions