Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to enforce error when function has no return in gcc?

Is it possible to enforce an error (to break the build) when a function definition has no return in its body?

Consider this function:

int sum(int a, int b) {
  int c = a + b;
  // and here should be return
};

When I compile with g++ -Wall, I get:

no return statement in function returning non-void [-Wreturn-type]

but I want this to be a hard error rather than a warning.

I'm currently using GCC 4.9.2, but if there's a solution for different version of GCC that would be helpful to know, too.

like image 589
BartekPL Avatar asked Mar 13 '17 09:03

BartekPL


People also ask

What happens if function has no return?

If no return statement appears in a function definition, control automatically returns to the calling function after the last statement of the called function is executed. In this case, the return value of the called function is undefined.

What happens if you forgot the return statement in a non-void function?

Such a function results in undefined behavior. Flowing off the end of a non-void function with no 'return' results in undefined behavior. The 'main' and 'wmain' functions are the exceptions.

What is __ Builtin_unreachable?

__builtin_unreachable() is typically meant to be an indication to the compiler optimizer that a certain section of the code would never be reachable. Other compilers seem to optimize out the section that contains this __builtin_unreachable(). However, the XLC compiler decides to substitute it with a trap instruction.


1 Answers

GCC has the option -Werror to turn all warnings into errors.

If you want to upgrade only a specific warning, you can use -Werror=X, where X is the warning type, without the -W prefix. In your particular case, that would be -Werror=return-type.

Note that this will only report missing return in a function that returns a value. If you want to enforce that return; must be explicitly written in a function returning void, you may be out of luck.

like image 102
Toby Speight Avatar answered Sep 23 '22 11:09

Toby Speight