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 asmain
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;
}
int, main are reserved for special meaning. So, we should not declare keyword as a variable name.
A valid variable name starts with a letter, followed by letters, digits, or underscores.
Rules for defining variablesA variable name can start with the alphabet, and underscore only. It can't start with a digit. No whitespace is allowed within the variable name. A variable name must not be any reserved word or keyword, e.g. int, goto, etc.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With