Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get return type of function in macro (C++)

I have ASSERT(x) macro and I want to call return if it asserts (in release configuration). To do this I need to know return type of function where I use this ASSERT. How to get it (I deal with C++03, LLVM GCC 4.2 compiler)?

My ASSERT macro:

#define ASSERT(x) \
    if(!(x)) {
        LOG ("ASSERT in %s: %d", __FILE__, __LINE__); \
        return /*return_type()*/; \
    }

PS: I tried return 0; - compiler shows error for void functions (and I didn't try it for complex returning types), if return; - error for non-void functions.

(Updated...)

I'll answer to werewindle, nyarlathotep and jdv-Jan de Vaan here. I use standard assert for debug configuration. But after beta-testing I still get crash reports from final customers, and in most cases I need to change my crashing functions:

ASSERT (_some_condition_);
if (!_some_condition_)      // add this return
    return _default_value_;

I understand, that my program may crash probably later (otherwise it will definitely crash in current function). Also I can't quit application because developing is for iPhone (apps may not quit programmatically there). So the easiest way would be to "auto return" when assertion failed.

like image 275
brigadir Avatar asked Feb 22 '23 00:02

brigadir


2 Answers

You can't determine the return type of the surrounding function in a Macro; macros are expanded by the preprocessor, which doesn't have this kind of information about the surroundings where these macros occur; it is basically just "searching and replacing" the macros. You would have to write separate macros for each return type.

But why not exit the program (i.e. calling the exit function)? Just returning from a function doesn't seem like a very robust error handling. Failed assertions should after all only occur when something is terribly wrong (meaning the program is in a state it was not designed to handle), so it is best to quit the program as soon as possible.

like image 181
codeling Avatar answered Mar 05 '23 15:03

codeling


There are no proper way to determine return type inside a function in C.

Also, if you somehow implement your variant of ASSERT it will lead to erroneous program behavior. Main idea of ASSERT: if it fails, then program is in undefined state and only proper way is to stop it now. I.e. by calling exit().

like image 25
werewindle Avatar answered Mar 05 '23 15:03

werewindle