typeof()表达式中的副作用 [英] Side effects within a typeof() expression
问题描述
typeof(expression)
,并且在里面使用带有副作用的表达式是合法的。因此,例如,你可以有这个C代码: int x = 0;
typeof(x ++)y;
在这种情况下,副作用被忽略,之后x仍然为零(这有意义的类型是一个只有编译时间的东西)。
然而, GCC文档说:
typeof的操作数的副作用为
,当且仅当它是可变修饰类型
的表达式或这种类型的名称。
这句话是什么意思?是否真的有可能编写带有副作用的 typeof
,并且副作用实际上是在运行时执行的?对我来说,这句话似乎表明了这一点。
是的,在某些情况下, code> typeof 已评估。正如文件所述,它需要处于可变更改类型之内。这是一种依赖于某些运行时值的类型,例如 int [x]
。
所以下面的代码是合法的,声明y的类型为 int [1]
,x的值为1之后:
int x = 0;
typeof(int [++ x])y;
当然,一般来说,对于可变修改类型同样如此,这只对局部变量声明合法功能)。
In GNUC C, you can use typeof(expression)
, and it is legal to use an expression with side effects inside. So for example you can have this C code:
int x = 0;
typeof(x++) y;
In this case, the side effect is ignored and x is still zero afterwards (this makes sense as types are a compile-time-only thing).
However, the GCC documentation says:
The operand of typeof is evaluated for its side effects if and only if it is an expression of variably modified type or the name of such a type.
What does this sentence mean? Is it really possible to write typeof
with a side effect and have the side effect actually be executed at runtime? For me, this sentence seems to indicate this.
Yes, it is possible in certain cases to have side-effects inside typeof
evaluated. As the documentation says, it needs to be within a "variably modified type". This is a type which depends on some runtime value, such as int[x]
.
So the following code is legal, declares y to be of type int[1]
, and x has the value 1 afterwards:
int x = 0;
typeof(int[++x]) y;
Of course, equally to variably modified types in general, this is only legal for local variable declarations (inside function).
这篇关于typeof()表达式中的副作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!