understanding C namespaces

前端 未结 4 1325
长情又很酷
长情又很酷 2020-11-29 03:31

Quoting from here,

In C, there are two different namespaces of types: a namespace of struct/union/enum tag names and a namespace of typedef names.

4条回答
  •  甜味超标
    2020-11-29 03:59

    To answer your two questions quick.

    Q1. In the first case, why is there a conflict? Do functions also belong to the typedef namespace?

    A1. Yes, identifiers for functions and typedef'ed types share the same namespace. So there's a conflict.

    Q2. In the second case, why is there no conflict at all? The function and the variable both are named four. Why does the compiler allow that? How is &four supposed to be resolved?

    A2. There's no conflict in your 2nd example even though the two identifiers named four belong to the same identifier namesapce, which is Ordinary namespace. Because the variable identifier four in the main is in a function scope, whereas the function identifier four in a file scope. So the latter one is hidden by the former one as the basic scope rule. If you move the variable four to the file scope(global) like below, you'll see an error.

    ...
    
    struct dummy four; // Error! there's a previous definition
                       // in this file scope(global).
    
    int main() {
        // struct dummy four; // Commented out.
    }
    

    Actually, there are four different identifier namespaces: Label, Tag, Member, and Ordinary. You can find details about them at https://en.cppreference.com/w/c/language/name_space

提交回复
热议问题