typedef没有替换为数据类型

Gok*_*rni 5 c c++ compiler-construction typedef compiler-errors

我对以下一段代码感到惊讶,

#include<stdio.h>
typedef int type;

int main( )
{
    type type = 10;
    printf( "%d", type );
}
Run Code Online (Sandbox Code Playgroud)

这经历了该计划的输出是10.

但是当我稍微改变代码时,

#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);
}
Run Code Online (Sandbox Code Playgroud)

在aCC编译器中:

"'type'用作类型,但尚未定义为类型."

在g ++编译器中:

"错误:预期`;' 之前f"

编译器是否在第二种情况下无法识别模式,因为此模式可能与变量的赋值,表达式的求值等有关,并且在第一种情况下,因为此模式仅在定义变量编译器识别它时使用.

Yu *_*Hao 11

typedef标识符与变量名一样,也有一个范围.后

type type = 10;
Run Code Online (Sandbox Code Playgroud)

变量会type影响类型名称type.例如,这段代码

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

因为同样的原因不能编译,在C++中,你可以::type用来引用类型名称:

typedef int type;
int main( )
{
    type type = 10;
    ::type n;  //compile fine
}
Run Code Online (Sandbox Code Playgroud)