c - __attribute__((pure)) 应用于 void 函数

标签 c gcc optimization attributes compiler-optimization

我有一个函数,它接受两个数组并将 pure 函数 (c_i = a_i/b_i) 的结果写入第三个数组:

inline
void    array_division      (ptrdiff_t nmemb,
                             double dest[static nmemb],
                             const double src1[static nmemb],
                             const double src2[static nmemb])
        __attribute__((nonnull, pure));

inline
void    array_division      (ptrdiff_t nmemb,
                             double dest[static nmemb],
                             const double src1[static nmemb],
                             const double src2[static nmemb])
{

        for (ptrdiff_t i = 0; i < nmemb; i++)
                dest[i] = src1[i] / src2[i];
}

GCC 抛出错误,因为它不期望纯函数返回 void

A pure function是一个作为其参数的函数,以及这些参数指向的值;如果在两次调用之间没有任何参数或它们指向的值发生变化,则它们应该是多余的并且可以省略该调用,评估为与前一次调用返回的相同值。

我的函数遵循所有这些规则:如果 3 个数组在两次函数调用之间没有变化,则可以完全删除函数调用;并且它们的计算结果相同(没有,因为它是 void)。

我认为 GCC 应该允许 __attibute__((pure)) 的这种用法是否正确?

我应该返回一个虚拟的 return 0; 以避免 GCC 提示吗?

编辑:

GCC 中的 BUG 状态:__ attribute __((pure)) to function with non-const pointers

最佳答案

至于为什么 return 0; 有效... 根据https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html#index-pure-function-attribute :

Because a pure function cannot have any observable side effects it does not make sense for such a function to return void. Declaring such a function is diagnosed.

但还要注意不能返回 void 的原因:它没有意义。您将放弃返回值的能力,以及纯函数的唯一合法目的。

The pure attribute prohibits a function from modifying the state of the program that is observable by means other than inspecting the function’s return value.

这意味着,例如,禁止用 pure 标记的函数在您传入的数组中设置条目。我有点惊讶它允许非常量指针,很多通过他们的分配更少。

至于当您欺骗 GCC 允许修改此类函数后会发生什么,我不确定。这取决于 GCC 指定在这种情况下它将执行的操作。

关于c - __attribute__((pure)) 应用于 void 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56923757/

相关文章:

optimization - 如何在 AMPL 中重新定义运行之间的集合

java - C 性能和编译选项

c++ - 什么是 __aeabi_unwind_cpp_pr1' 以及如何避免它?

基于 c 中的 EBP 从堆栈帧调用函数及其参数

c - R 中是否有比 readLines 更快的东西 - 或者我如何找出读取连接速度如此慢的原因?

c - WAF - ntldd - 无法链接静态系统库

c++ - 使用 g++-9 设置堆栈大小无效

java - Lwjgl如何简化高度图以获得更高的fps?

c - 优化轴对齐边界框检查

c - 使用openGL ES 2.0结合其他画线功能进行字体渲染(Freetype)不起作用