#define和typedef在使用其名称定义变量

时间:2017-06-23 10:49:21

标签: c++ typedef

这是对这个问题的跟进here

typedef int foo;
#define bar int

int main() {
    bool foo = true; // ok
    bool bar = true; // fail
}

typedef有效,但我很想知道这里的typedef如何运作?

最终编译代码与foo的关系如何?根据几个答案,typedef是别名,别名允许被遮蔽。因此代码有效。

有人可以解释一下吗?

3 个答案:

答案 0 :(得分:1)

通常允许使用类型名称来定义具有相同名称的变量我的意思是:

typedef int foo; // can't be in the same scope as the below definitions
struct foo { foo(int) {} }; // same thing as above

int foo = 0; // ok
foo bar = 1; // ok
foo foo = 2; // ok

但使用#define foo int时,没有foo类型/别名:

#define foo int
int foo = 0; // fail
foo bar = 1; // ok
foo foo = 2; // fail

以上实际上是(在预处理器运行之后):

int int = 0; // fail
int bar = 1; // ok
int int = 2; // fail

如果您有另一个定义bool foo = true;,那么它将变为bool int = true;,但也无法编译。

但有一个例外:int是保留关键字,这意味着您无法使用该名称定义任何变量。但如果它是另一种类型struct bar{};,则该部分将编译。

答案 1 :(得分:0)

第一个可行,因为您提供的是类型而不使用typedef。第二个失败,因为宏将int替换为bar。

typedef int foo;
#define bar int

int main() {
    bool foo = true; // ok   
           // You have created a new bool variable named foo.
           // There is no relation to the typedef foo.
    bool bar = true; // fail
           //  Essentially you are saying
           //           bool int = true;
           //  which doesn't compile - you can't have a variable named
           //  int because it's a reserved keyword.
}

答案 2 :(得分:0)

我的变量可能与类型名称相同:您有一个未使用的类型foo和一个类型为bool的变量foo。

相关问题