Search code examples
c++typesundefined-behaviorlinkage

Type identity rule and its violation


Below some code violating the type identity rule (on ideone):

#include <iostream>

void foo()
{
    typedef int I;
    extern I a; //now a is denoting an entity, which is a member of global scope
    std::cout << a;
}

typedef char I;
I a; //definition of a

int main()
{
    foo();
}

The type identity rule(sec. 3.6/10 N3797):

After all adjustments of types (during which typedefs (7.1.3) are replaced by their definitions), the types specified by all declarations referring to a given variable or function shall be identical, except that declarations for an array object can specify array types that differ by the presence or absence of a major array bound (8.3.4). A violation of this rule on type identity does not require a diagnostic.

I understand that violation of that rule does not require a diagnostic. But why not?


Solution

  • The quoted rule means that your violation invokes Undefined Behavior.

    The reasons for not fully-specifying behavior are:

    • Ease of implementation.
    • Efficiency of the program.
    • Catering to differing existing implementations.
    • Allowing for extensions and future evolution.

    In your case, most object-file types will not contain the neccessary information to diagnose your error if it is distributed acrross multiple implementation units.
    That makes it hard to impossible to diagnose.

    Anyway, as C++ does not contain any method to access different objects with the same name, putting that information into the object files is not a good idea, especially as the linker would then have to know all the rules C++ uses for exceptions and corner-cases.