Reputation: 2858
For my systems programming class we're doing a lot of programming in C and are required to error check most functions as we are currently learning to program with pthreads.
The reason I say this is not really homework, is that it is far above and beyond what is expected for this class. Simply checking each function individually is more than satisfactory. I just feel this is a time-consuming and messy method and hope for a neater 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 required parameters for that function, along with a desired return value (in this case the correct one), and performs the following.
if(function_name(param1, param2, ...) != desired_return_value) {
fprintf(stderr, "program_name: function_name() failed\n");
perror("function_name(): ");
}
Is this possible? It's hardly required by our course, but it just irks me that virtually ever function I write has to have 4 lines of code to error check it. It makes it bloody hard to read.
Even some other suggestions would be good. I'm just trying to increase readability, so if this is totally the wrong direction, some correct direction would be much appreciated.
EDIT: This should compile under the gnu99 standard ideally :P
EDIT 2: In response to James McNellis: The errors from our functions do not (I believe in this case), need to be handled. Notification only needs to be supplied. We have covered nothing on handling thread/process related errors (which is this subject in a nutshell).
Upvotes: 3
Views: 3007
Reputation: 355049
Writing generic code in C without using macros isn't the easiest thing to do.
For a (very) basic solution using a variadic macro:
#define CALL_AND_CHECK(f, r, ...) \
do { \
if (f(__VA_ARGS__) != r) \
{ \
fprintf(stderr, "program_name: " #f "() failed\n"); \
perror(#f "(): "); \
} \
} while (0)
(See Why are there sometimes meaningless do/while and if/else statements in C and C++ macros? for why the "meaningless" do/while loop is used)
Note that printing out an error message and not actually handling the error is almost certainly a bad idea. Generally, different errors need to be handled in different ways, so generic code like this may not be particularly useful. If you don't want to try and recover from any of these errors, you could exit()
, which might be okay for an assignment, though in a real-world program you wouldn't want to do that.
Upvotes: 13