Search code examples
c++macroslanguage-lawyerconditional-compilation

#if ! SOME_MACROS equivalent with #ifndef SOME_MACROS if SOME_MACROS always has numerical value


May be this is duplicate, I can't find similar question.

My surprise that, following code works for all three big compiler without error

#include <cstdio>

int main() {
    #if !_LIBCPP_VERSION 
        std::printf("_LIBCPP_VERSION not defined");
    #else
        std::printf("_LIBCPP_VERSION defined and equal to %d", _LIBCPP_VERSION);
    #endif

    #ifndef _LIBCPP_VERSION
        std::printf("_LIBCPP_VERSION not defined");

    #else
        std::printf("_LIBCPP_VERSION defined and equal to %d", _LIBCPP_VERSION);

    #endif
}

Link to godbolt

My question is that: There check #if !_LIBCPP_VERSION - is always similar with #ifndef _LIBCPP_VERSION by standard C or C++?


Solution

  • They are not equivalent for numerical values.

    SOME_MACROS #if !SOME_MACROS #ifndef SOME_MACROS
    x True False
    1 False False
    0 True False
    undef True True

    Now, you said you only care about numerical values, so only the middle rows are relevant here. Yet we see a difference in those two rows.