understanding C namespaces

But the crucial point on your examples isn't about namespace, but the scope of the names.

In name.c, both long2 are "ordinary identifiers" (share the same name space), and both of them are defined in the same scope, so there is a conflict. (C99 §6.7/3)

If name2.c, the local variable four is in a scope deeper than the function four, so the variable hides the function four (C99 §6.2.1/4).


Your 2nd example does not show "no conflict". There is a conflict! Try this:

#include <stdio.h>
int four(void) { return 4; }
struct dummy { int member; };
int main(void) {
    struct dummy four;
    four.member = four();
}

And now this

#include <stdio.h>
int four(void) { return 4; }
struct dummy { int member; };
int main(void) {
    int (*fx)(void) = four; /* "save" function */
    struct dummy four;     /* hide it         */
    four.member = fx();    /* use "hidden" fx */
}

In your 2nd example, the variable four hides the function four().


C has four different name spaces for identifiers:

  • Label names (the goto type).
  • Tags (names of structures, unions and enumerations).
  • Members of structures and unions (these have a separate namespace per structure/union).
  • All other identifiers (function names, object names, type(def) names, enumeration constants, etc).

See also C99 6.2.3.

So your two question can be answered as:

  1. Yes, function names and typedef names share the same name space.
  2. No conflict, because the compiler will use scope rules (for function or object names). The identifier in main is said to shadow the global function name, something your compiler will warn you about if you set the warning levels high enough.

Tags:

C

Namespaces