说我有一些功能
unsigned int my_random_value(unsigned int a);
返回 0, 1, ..., a - 1 范围内的值。我想断言 GCC 返回值将在这个范围内,但我不知道如何很好地做到这一点。通过包装这个函数,GCC 可以通过
注意到这一点unsigned int my_random_value(unsigned int a);
static inline
unsigned int my_random_value_wrapper(unsigned int a)
{
unsigned int ret = my_random_value(a);
if (ret >= a)
__builtin_unreachable();
return ret;
}
但这在头文件中会相当大,并且不允许我使用
my_random_value
直接访问此函数。有没有更好的方法来做到这一点,也许通过属性?
是的,您可以使用 GCC 属性来做到这一点。您可以使用
__attribute__((__returns_twice__))
属性注释您的函数,以便它可能返回多次。这样 GCC 就会知道它不应该对返回值做出任何假设。
unsigned int my_random_value(unsigned int a) __attribute__((__returns_twice__));
static inline
unsigned int my_random_value_assert(unsigned int a)
{
unsigned int ret = my_random_value(a);
__builtin_expect(ret < a, 1); // This helps the compiler with branch prediction
return ret;
}
通过使用
__builtin_expect
,您可以向编译器暗示比较的可能结果。