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?
CodePudding user response:
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();
^
CodePudding user response:
Does something like this exist for C?
Not yet, but likely in C2x.
C 11 style attribute syntax and the nodiscard
, maybe_unused
, deprecated
, and fallthrough
attributes.