简体   繁体   English

typeof()表达式中的副作用

[英]Side effects within a typeof() expression

In GNUC C, you can use typeof(expression) , and it is legal to use an expression with side effects inside. 在GNUC C中,您可以使用typeof(expression) ,并且使用内部具有副作用的表达式是合法的。 So for example you can have this C code: 例如,你可以拥有这个C代码:

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). 在这种情况下,副作用被忽略,之后x仍然为零(这是有道理的,因为类型只是编译时的事情)。

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. 当且仅当它是可变修改类型的表达式或这种类型的名称时,才评估typeof的操作数的副作用。

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? 是否真的可以编写带有副作用的typeof并且副作用实际上是在运行时执行的? For me, this sentence seems to indicate this. 对我来说,这句话似乎表明了这一点。

Yes, it is possible in certain cases to have side-effects inside typeof evaluated. 是的,有可能在某些情况下有副作用内typeof评估。 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] . 这是一种取决于某些运行时值的类型,例如int[x]

So the following code is legal, declares y to be of type int[1] , and x has the value 1 afterwards: 所以下面的代码是合法的,声明y是int[1]类型,x后面的值是1:

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). 当然,对于一般的可变修改类型,这仅对局部变量声明(内部函数)是合法的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM