Error codes in C

Here is some brief C-code that has a macro as an error notification function:

#include <stdio.h>
#include <stdlib.h>

#define FAIL_IF(EXP, MSG) ({ if (EXP) { printf(MSG "\n"); exit(EXIT_FAILURE); }})

int main (int argc, char *argv[]) {
  printf("Usage: %s input_file\n\n", argv[0]);
  FAIL_IF(argc < 2, "Too few arguments supplied: expecting name of input file.");
  return 0;
}

I learned that using macros as functions is not recommended. With the suggested error printing and exiting with EXIT_FAILURE, can anyone concur whether this is good programming practice?

1 Like

I'm fine with that code, but others may not be. It's essentially what the language-defined assert macro does.

1 Like

ditto, no issue with this, if you want to go the whole hog ...

#define FAIL_IF(EXP, MSG) ({ if (EXP) { printf( "%s:%d: %s\n", __FILE__, __LINE__, MSG ); exit(EXIT_FAILURE); }})
1 Like