简体   繁体   中英

effficient way to implement try/catch in C

I want to do something like the following in C:

doSomthing(test_arg1); // first time
check_if_everything_good();

doSomething(test_arg2); // second time
check_if_everything_good();

doSomething(test_arg3); // third time
check_if_everything_good();

The idea is that after I call doSomething(), I want to make sure the function call didn't corrupt anything else, by calling check_if_everything_good(). In case doSomething() corrupted something, check_if_everything_good() returns before the second doSomething() call.

I however want to avoid calling check_if_everything_good() each time after doSomething() {check_if_everything_good is expensive}. Is there a way I can efficiently achieve this in C? Something maybe like a try/catch in java

Assuming that check_if_everything_good is only needed for debug/diagnostic purposes in a development environment, then you could do something like this:

#ifndef NDEBUG
#define check_if_everything_good() do_check_if_everything_good()
#else
#define check_if_everything_good()
#endif

NDEBUG is a define typically defined by the compiler in a "release" (or "not a debug") build, so we use that here to "only do this when it actually makes sense".

You can use set jump and longjump

read this http://www.di.unipi.it/~nids/docs/longjump_try_trow_catch.html

and you can also use goto statment

http://www.roseindia.net/c-tutorials/c-goto-statement.shtml

If what you want is to be able to compile out the checks for production code, then Mats' suggestion works fine. The equivalent solution without creating your own macro is to simply change your check function to return 0 for failure and non-zero for success, and wrap the call with an assert() .

assert(check_if_everything_good());

If you want to sometimes perform the check but not always, because it impacts performance, you can use random sampling. In this case, it just means you call rand() , and if the returned value is within some range, you perform the check, and otherwise you skip the check.

#define maybe_check_everything() \
    do { \
        if (CHECK_ALWAYS || (CHECK_THRESHOLD ? rand() < CHECK_THRESHOLD : 0)) \
            check_if_everything_good(); \
    } while (0)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM