cscoping

When parameter name equals function name: who wins?


(I have this uneasy feeling that I've asked this before, but now I can't find it. Feel free to close and redirect this question if so...)

In C, assume I have a function named thing() and some other function that uses thing as a formal parameter:

thing_t *thing(int id) { ... function that returns a *thing_t ... }

void foo(thing_t *thing) { ... function that takes a *thing_t as an argument ... }

Inside the body of foo(), is there any guarantee that thing refers to the passed-in parameter as opposed to the function of the same name? Do any of the C specifications have anything to say about this?

(And yes, I'd agree that this is dubious coding style...)


Solution

  • The definition of the function thing declares thing as an identifier with file scope, per C 2018 6.2.1 4. Its scope extends from its declaration (specifically, from the end of its declarator, *thing(int id)) to the end of the translation unit.

    The definition of the parameter thing in the definition of foo declares thing as an identifier with block scope, also per 6.2.1 4. Its scope extends from its declaration to the end of the block that is the body of the function definition.

    Then the final sentences of 6.2.1 4 tells us that within foo, thing refers to the parameter, not the function:

    If an identifier designates two different entities in the same name space, the scopes might overlap. If so, the scope of one entity (the inner scope) will end strictly before the scope of the other entity (the outer scope). Within the inner scope, the identifier designates the entity declared in the inner scope; the entity declared in the outer scope is hidden (and not visible) within the inner scope.