cgccbitwise-operatorsbitflags

-D name=definition and bitwise operator


I am trying to understand how the next calculation is performed.

For example, if this is my terminal command

gcc ex2.c -D b+=2

Why do I get 5?

#include <stdio.h>

int main() 
{
#ifdef b
    printf("%d\n", 2 b | ~ 2 b);
#endif
    return 0;
}

2 b mean 2*b ?

~ 2 b mean 2*b and then ~ ?


Solution

  • compiling with gcc ex2.c -D b+=2 define b as +2 so the source

    #include <stdio.h>
    
    int main() 
    {
    #ifdef b
        printf("%d\n", 2 b | ~ 2 b);
    #endif
        return 0;
    }
    

    is like

    #include <stdio.h>
    
    int main()
    {
    
        printf("%d\n", 2 + 2 | ~ 2 + 2);
    
        return 0;
    }
    

    and for me that prints -1


    to see the result after the preprocessing use the option -E :

    /tmp % gcc ex2.c -E -D b+=2
    <command-line>: warning: missing whitespace after the macro name
    ...
    # 2 "ex2.c" 2
    
    int main()
    {
    
        printf("%d\n", 2 + 2 | ~ 2 + 2);
    
        return 0;
    }