Search code examples
c++identifierreserved-wordsvariable-names

is it valid to use standard library function name as identifier in C++?


Consider following program:

#include <cstdio>
int main()
{
    int printf=9;
    std::printf("%d",printf);
}

Is it fine to use built in function name as an identifier in variable declaration? Is this well defined program? I mean is behaviour of above program well defined? I am curious to know whether the C++ standard allows to use standard function names as identifiers of variables


Solution

  • It's well-formed because neither std::printf nor ::printf (which may also have been declared by <cstdio>!) are declared in the same scope as your integer, which therefore takes automatic precedence for the duration of the block.

    [C++14: 3.3.1/1]: [..] To determine the scope of a declaration, it is sometimes convenient to refer to the potential scope of a declaration. The scope of a declaration is the same as its potential scope unless the potential scope contains another declaration of the same name. In that case, the potential scope of the declaration in the inner (contained) declarative region is excluded from the scope of the declaration in the outer (containing) declarative region.

    For example, you generally wouldn't be able to do this at namespace scope.

    It's well-defined because the names of entities in the standard library are not inherently reserved names:

    [C++14: 2.11/3]: In addition, some identifiers are reserved for use by C++ implementations and standard libraries (17.6.4.3.2) and shall not be used otherwise; no diagnostic is required.

    [C++14: 17.6.4.3.2/1]: Certain sets of names and function signatures are always reserved to the implementation:

    • Each name that contains a double underscore _ _ or begins with an underscore followed by an uppercase letter (2.12) is reserved to the implementation for any use.
    • Each name that begins with an underscore is reserved to the implementation for use as a name in the global namespace.