开发者

How to detect no-return statement from a function

I have a function which returns non-void. On the caller side, I want to detect whether a return statement was called in original function or not.

I know, that it is not allowed to have non-void function return nothing and it would thro开发者_StackOverfloww up a warning in gcc. But I want to print a runtime error based on whether return was called or the control reached the end of function.

The callee is defined by user. I just provide the declaration. So, basically I want to ensure that the implementer of callee function, doesn't skip "return" statement.


You can't determine how a function returns from the caller (other than whether it throws an exception or what it returns). The only thing you can do is prevent the function from returning explicitly using that compiler warning or put a run-time error call at the end of the function that you don't want to have control fall off the end of. One trick that you might be able to do is have the return type from the function have a default constructor which gives a run-time error; any return statements would need to use some other constructor. Once you do that, though, you might as well just add an error call to the end of the function or change the return type to get the GCC warning.


Sounds like what you really want to do is return an error code, or throw an exception


If a function with a non-void return type doesn't return, the behaviour is undefined.

This means you can't check at runtime for something that should really be a compiler error (The C# compiler considers it an error).

If you'd like to know if your function reaches the end, make it return a known value or throw an exception.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜