Search code examples
c++ccompiler-errorstypedef

typedef did not replaced with the datatype


I was surprised with the following piece of code,

#include<stdio.h>
typedef int type;

int main( )
{
    type type = 10;
    printf( "%d", type );
}

This went through and output of the program is 10.

But when I changed the code slightly as below,

#include<stdio.h>
typedef int type;

int main()
{
    type type = 10;
    float f = 10.9898;
    int x;
    x = (type) f;
    printf( "%d, %d", type, x);
}

in aCC compiler:

"'type' is used as a type, but has not been defined as a type."

in g++ compiler:

"error: expected `;' before f"

Is it that the compiler did not recognize the pattern in the second case, as this pattern can be related to assignment of a variable, evaluation of an expression etc and in the first case as this pattern is only used while defining a variable compiler recognized it.


Solution

  • typedef identifiers, like variable names, also has a scope. After

    type type = 10;
    

    the variable type shadows the type name type. For instance, this code

    typedef int type;
    int main( )
    {
        type type = 10;
        type n;   //compile error, type is not a type name
    }
    

    won't compile for the same reason, in C++, you can use ::type to refer to the type name:

    typedef int type;
    int main( )
    {
        type type = 10;
        ::type n;  //compile fine
    }