ADBlock is blocking some content on the site

ADBlock errore

How do I define a value that is the sum of other predefined values in C?

StackOverflow https://stackoverflow.com/questions/20301800


How can I use #define to say that one value consists of the sum of two other values. Would it be allowed and good practice in C to do something like this?

#define VALUE_A 2
#define VALUE_B 2
#define SUM_A_B (VALUE_A + VALUE_B)

If not, what should I do to achieve this functionality?

Solution 2

If you just need that for integer constants (type int) you may use enumerations for this type of constants

enum { SUM_A_B = (VALUE_A + VALUE_B), };

possible advantages:

  • the sum is only evaluated once by the compiler. This is not a big deal for modern compilers if this is only such a simple sum, but could make a small difference when you are using more complicated expressions
  • even nowadays compiler errors and debugging information isn't that good for values coming from the preprocessor. Enumeration constants usually can be traced well.

A disadvantage is that the value itself is not accessible in the preprocessor itself. So you can't do #if/#else constructs with it. But you could at least still define it as

#define SUM_A_B SUM_A_B

So #ifdef/#else constructs would still work.


The Linux and GCC header files do it routinely, if that's a vote of confidence. e.g.:

$ grep -r 'define.*+' /usr/include/
/usr/include/linux/fdreg.h:#define FD_STATUS    (4 + FD_IOPORT )
/usr/include/linux/elf.h:#define PT_GNU_STACK   (PT_LOOS + 0x474e551)
/usr/include/i386-linux-gnu/asm/unistd_32.h:#define __NR_timer_settime  (__NR_timer_create+1)


Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow