Does C have a [[nodiscard]] mechanism to warn when values are ignored?

Viewed 78

In C++ we can decorate our return types with "[[nodiscard]]" which triggers a compiler warning if the results are unused.

This is particularly useful to enforce error codes

auto dont_forget_to_check = do_something_important();
assert(dont_forget_to_check);

Does something like this exist for C?

2 Answers

There's no standard way to do this, but gcc does support the warn_unused_result attribute for this.

__attribute__ ((warn_unused_result))
int foo()
{
    return 5;
}

int main()
{
    foo();
    return 0;
}

Compiler output:

[dbush@db-centos7 ~]$ gcc -g -Wall -Wextra -o x1 x1.c
x1.c: In function ‘main’:
x1.c:11:8: warning: ignoring return value of ‘foo’, declared with attribute warn_unused_result [-Wunused-result]
     foo();
        ^
Related