断言GCC返回值在某个范围内

问题描述 投票:0回答:1

说我有一些功能

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
直接访问此函数。有没有更好的方法来做到这一点,也许通过属性?

c gcc
1个回答
0
投票

是的,您可以使用 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
,您可以向编译器暗示比较的可能结果。

© www.soinside.com 2019 - 2024. All rights reserved.