使用名称定义变量时

使用名称定义变量时

本文介绍了使用名称定义变量时#define 和 typedef 的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是对这个问题的跟进这里.>

This is a follow up to this question right here.

typedef int foo;
#define bar int

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

typedef 可以工作,但我很想知道这里的 typedef 是如何工作的?

the typedef works, but I am curious to know how can the typedef here work?

关于 foo 的最终编译代码是什么样的?根据少数答案, typedef 是别名,允许对别名进行遮蔽.因此代码有效.

How does the final compiled code looks like with respect to foo? According to few answers, typedef is an alias and alias is allowed to be shadowed. Hence the code works.

谁能解释一下?

推荐答案

一般允许使用类型名来定义同名变量 我的意思是这样的:

Type names in general are allowed to be used to define a variable with the same name What I mean is this:

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 类型/别名:

But with #define foo int, there is no foo type/alias:

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

上面其实是(预处理器运行后):

The above is actually (after the preprocessor runs):

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

如果你有另一个定义,bool foo = true;,那么它就会变成bool int = true;,同样编译失败.

If you had another definition, bool foo = true;, then it will become bool int = true;, which also fails to compile.

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

But there is an exception: int is a reserved keyword, which means you can't define any variables with that name. But if it were another type like struct bar{};, then that part will compile.

这篇关于使用名称定义变量时#define 和 typedef 的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 21:12