您是否有示例“...使用 __auto_type 时仅评估一次,但如果使用 typeof 则评估两次。”?
Do you have examples to "...it is evaluated only once when using __auto_type, but twice if typeof is used. "?
If the argument to the macro has variably modified type, it is
evaluated only once when using __auto_type, but twice if typeof is
used.
从该文件的末尾开始:https://gcc.gnu.org/onlinedocs/gcc/Typeof.html
如果使用 typeof
代替 __auto_type
,有人能给我提供在运行时导致代码中断的情况示例吗?
您在评论中留言
note that typeof is usually removed in build time
这似乎强调了您困惑的症结所在。虽然 typeof
是 GNU 扩展,而不是标准 C,但它类似于 C 的 sizeof
,它只是 通常 在构建时计算。正如您链接到的 GNU 文档所说,
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
本身是否对应于运行时代码并不是真正的重点(尽管在那种情况下它可能 对应于运行时代码);关键是宏参数是在 typeof
操作的上下文中在运行时评估的。如果该评估产生任何副作用,那么 typeof
和 __auto_type
在应用这些副作用的次数方面存在差异,甚至可能在副作用是什么方面存在差异。
构造一个具有 variably-modified 类型且其计算产生 non-trivial 副作用的表达式的示例确实有点棘手,但我们可以在这里求助于旧的自动递增/自动递减.例如:
#include <stdio.h>
#define TYPEOF_EX(p) do { \
__typeof__(p) _q = (p); \
printf("typeof yields: %d\n", (*_q)[1]); \
} while (0)
#define AUTOTYPE_EX(p) do { \
__auto_type _q = (p); \
printf("__auto_type yields: %d\n", (*_q)[1]); \
} while (0)
int main(void) {
int x = 3;
int y = 5;
int a[x][y];
int (*p)[y];
for (int i = 0; i < x; i++) {
for (int j = 0; j < y; j++) {
a[i][j] = i * y + j;
}
}
p = a;
TYPEOF_EX(++p);
p = a;
AUTOTYPE_EX(++p);
}
该程序为我生成以下输出:
typeof yields: 11
__auto_type yields: 6
If the argument to the macro has variably modified type, it is evaluated only once when using __auto_type, but twice if typeof is used.
从该文件的末尾开始:https://gcc.gnu.org/onlinedocs/gcc/Typeof.html
如果使用 typeof
代替 __auto_type
,有人能给我提供在运行时导致代码中断的情况示例吗?
您在评论中留言
note that typeof is usually removed in build time
这似乎强调了您困惑的症结所在。虽然 typeof
是 GNU 扩展,而不是标准 C,但它类似于 C 的 sizeof
,它只是 通常 在构建时计算。正如您链接到的 GNU 文档所说,
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
本身是否对应于运行时代码并不是真正的重点(尽管在那种情况下它可能 对应于运行时代码);关键是宏参数是在 typeof
操作的上下文中在运行时评估的。如果该评估产生任何副作用,那么 typeof
和 __auto_type
在应用这些副作用的次数方面存在差异,甚至可能在副作用是什么方面存在差异。
构造一个具有 variably-modified 类型且其计算产生 non-trivial 副作用的表达式的示例确实有点棘手,但我们可以在这里求助于旧的自动递增/自动递减.例如:
#include <stdio.h>
#define TYPEOF_EX(p) do { \
__typeof__(p) _q = (p); \
printf("typeof yields: %d\n", (*_q)[1]); \
} while (0)
#define AUTOTYPE_EX(p) do { \
__auto_type _q = (p); \
printf("__auto_type yields: %d\n", (*_q)[1]); \
} while (0)
int main(void) {
int x = 3;
int y = 5;
int a[x][y];
int (*p)[y];
for (int i = 0; i < x; i++) {
for (int j = 0; j < y; j++) {
a[i][j] = i * y + j;
}
}
p = a;
TYPEOF_EX(++p);
p = a;
AUTOTYPE_EX(++p);
}
该程序为我生成以下输出:
typeof yields: 11
__auto_type yields: 6