Home > Mobile >  Is there an attribute in C to throw a fatal compiler error upon ignored return type?
Is there an attribute in C to throw a fatal compiler error upon ignored return type?

Time:12-04

I am looking for a harsher version of [[nodiscard]] that throws an fatal error instead of a warning when a return value is ignored. So for example:

[[harshnodiscard]] int getSize() { return 0; } 

Any code that ignores the return value of getSize should not compile.

Is there any functionality for this?

CodePudding user response:

Yes, there is a feature in C 17 called [[nodiscard("message")]] that allows you to specify an error message that will be thrown when a return value is ignored. Here is an example:

    [[nodiscard("Error: return value must not be ignored")]]
int foo() {
  // Some code here
  return 5;
}

In this code, if the return value of the foo function is ignored, the compiler will throw an error with the message "Error: return value must not be ignored".

CodePudding user response:

There is no built-in attribute in C to throw a fatal compiler error when a return value is ignored. However, you could potentially achieve this by using a combination of the [[nodiscard]] attribute and a static_assert statement.

For example:

[[nodiscard]] int getSize() {
static_assert(false, "return value of getSize() was ignored");
return 0;
}

This will cause the compiler to throw an error when the return value of getSize() is ignored. You could also add a custom error message to the static_assert statement to make the error more informative.

For example:

[[nodiscard]] int getSize() {
static_assert(false, "return value of getSize() must not be ignored");
return 0;
}

This will cause the compiler to throw an error with the message "return value of getSize() must not be ignored" when the return value of getSize() is ignored. Note that this approach will not work if the return value is ignored in a conditional statement that is never executed.

For example:

if (false) {
getSize(); // return value will be ignored, but no error will be thrown
}

In this case, the static_assert statement will not be executed because the if statement is never executed, so no error will be thrown.

  • Related