cpreprocessorcompiler-directives

Does C preprocessor directives recompute each time?


I have this line of code:

#define ALPHABET_SIZE 'z' - 'a' + 1

When I hover over ALPHABET_SIZE anywhere in my code it tells me that it expands to 'z' - 'a' + 1. So I wondered if this expression has to be recomputed each time I use ALPHABET_SIZE in my code? If so, how can I prevent the recomputation?


Solution

  • #define ALPHABET_SIZE 'z' - 'a' + 1
    

    The pre-processor replaces each ALPHABET_SIZE

    With

    'z' - 'a' + 1
    

    The compiler then will most probably perform Constant folding optimization replacing the computation with 26.


    Demo https://godbolt.org/z/Mo46db, the expression is replaced by 26 with gcc 10.2