C Error checking function

For my system programming class, we do a lot of C programming and require the error to test most functions, since we are currently learning to program using pthreads.

The reason I say this is not real homework is because it is much higher and higher than what is expected for this class. Just checking each function individually is more than satisfactory. I just think that this is a time-consuming and messy method and we hope for a more accurate solution.

I was wondering if anyone could show me how to write a function that takes any C function as a parameter, followed by all the necessary parameters for this function, as well as the desired return value (correct in this case) and does the following.

if(function_name(param1, param2, ...) != desired_return_value) {
    fprintf(stderr, "program_name: function_name() failed\n");
    perror("function_name(): ");
}

Is it possible? This is hardly required in our course, but it just annoys me that almost any function I write should contain 4 lines of code to test this. It's hard to read.

Even some other suggestions would be nice. I'm just trying to increase readability, so if this is a completely wrong direction, it will be useful to evaluate the right direction.

EDIT: This should be compiled under the gnu99 standard, ideally: P

EDIT 2: : ( , ), . . , / ( ).

+3
1

C - .

() :

#define CALL_AND_CHECK(f, r, ...)                                \
    do {                                                         \
        if (f(__VA_ARGS__) != r)                                 \
        {                                                        \
            fprintf(stderr, "program_name: " #f "() failed\n");  \
            perror(#f "(): ");                                   \
        }                                                        \
    } while (0)

(. do/while if/else C ++?, "" do/while )

, . , -, , , . - , exit(), , .

+13

Source: https://habr.com/ru/post/1764617/


All Articles