Can local variables and functions have the same names in C?

前端 未结 4 1191
予麋鹿
予麋鹿 2021-01-04 10:30

Suppose I have a single .c file in which I have a local variable a. Can I also have a function in that c file which has t

4条回答
  •  渐次进展
    2021-01-04 11:16

    You can declare local variables with the same name as a global variable, but the local variable will shadow the global. As long as your local a is in scope, the symbol a refers to your local variable.

    Some languages allow to refer to the global symbols via special syntax, such as ::a or .a. C is not one of these languages.

    (As a side note: You shouldn't give global functions names that are likely to interfere with locals. Names of locals are usually short and don't carry much information - it is not needed, bacause the context is clear. Global variables have to share one big namespace with other variables. It is recommended to provide a bit of context in your name in order to avoid name clashes and shadowing.)

提交回复
热议问题