gpt4 book ai didi

c - 以编程方式确定变量的值是在编译时还是在运行时计算的

转载 作者:行者123 更新时间:2023-12-04 00:53:36 25 4
gpt4 key购买 nike

在 C 语言中有没有一种方法可以通过编程确定变量的值是在编译时还是在运行时计算的?

例子:

const double a = 2.0;
const double b = 3.0;
double c1 = a / b; // done at compile time (constant folding / propagation)
double c2 = *(volatile double*)&a / *(volatile double*)&b; // done at run time
compute_time_t c1_ct = compute_time(c1);
compute_time_t c2_ct = compute_time(c2);
assert(c1_ct == COMPILE_TIME);
assert(c2_ct == RUN_TIME);

最佳答案

在 C 中(如 in,由语言标准定义),不,没有办法。

但是,您可以使用特定于编译器的方法来真正接近实现您想要的目标。最著名的,as @Nate Eldredge notes在注释中,是 GCC 和 Clang 中可用的内置函数 __builtin_constant_p()

这是相关摘录 from the GCC doc :

Built-in Function: int __builtin_constant_p (exp)

You can use the built-in function __builtin_constant_p to determine if a value is known to be constant at compile time and hence that GCC can perform constant-folding on expressions involving that value. The argument of the function is the value to test. The function returns the integer 1 if the argument is known to be a compile-time constant and 0 if it is not known to be a compile-time constant. A return of 0 does not indicate that the value is not a constant, but merely that GCC cannot prove it is a constant with the specified value of the -O option.

请注意此函数不能保证检测到所有 编译时常量,但只能检测到 GCC 能够证明的常量。不同的优化级别可能会改变此函数返回的结果。

此内置函数在 glibc 中广泛用于优化目的 (example),通常结果仅在其为 1 时才可信,否则假设为非常量:

void somefunc(int x) {
if (__builtin_constant_p(x)) {
// Perform optimized operation knowing x is a compile-time constant.
} else {
// Assume x is not a compile-time constant.
}
}

使用你自己的例子:

const double a = 2.0;
const double b = 3.0;
double c1 = a / b; // done at compile time (constant folding / propagation)
double c2 = *(volatile double*)&a / *(volatile double*)&b; // done at run time

assert(__builtin_constant_p(c1));
assert(!__builtin_constant_p(c2));

关于c - 以编程方式确定变量的值是在编译时还是在运行时计算的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64454631/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com