6
#define MY_CONST 20
#define OTHER_CONST 10

My code only makes sense if MY_CONST > OTHER_CONST. How can I guarantee this with the preprocessor? Is there any command like this?

#assert MY_CONST < OTHER_CONST
2
  • 3
    #define MY_CONST OTHER_CONST + 10 ? Jun 15, 2018 at 13:52
  • @SanderDeDycker In my case, the code is clearer when these values are defined separately
    – Anna
    Jun 15, 2018 at 13:53

2 Answers 2

15

Is there any command like this?

#assert MY_CONST < OTHER_CONST

#if OTHER_CONST >= MY_CONST
#error "Error, OTHER_CONST >= MY_CONST"
#endif
0

as @attersson said #if will do it. (as a good habbit try to parenthesize your macros to guarantee order of evaluation for more complex expressions. this answer shows why.)

#include <stdio.h>
#define A 10
#define B 11
#if (A) > (B)
  #define RES "yes"
#else
  #define RES "no"
#endif

int
main(int argc, char *argv[])
{
        printf("is A larger? %s\n", RES);
        return 0;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.