Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are main and fopen valid variable names?

Tags:

c

keyword

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;
}
like image 915
Jeegar Patel Avatar asked Sep 17 '14 13:09

Jeegar Patel


People also ask

Is Main () a valid variable name?

int, main are reserved for special meaning. So, we should not declare keyword as a variable name.

Which variables names are valid?

A valid variable name starts with a letter, followed by letters, digits, or underscores.

Can we have variable name main in C?

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.


1 Answers

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.

like image 96
ouah Avatar answered Oct 04 '22 21:10

ouah