Gi5
Gi5

Reputation: 83

-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 ~ ?

Upvotes: 1

Views: 137

Answers (2)

KamilCuk
KamilCuk

Reputation: 141698

This is weird that it works and looks like a bug (or feature) from gcc and clang in parsing command line arguments.

Looks like gcc substitutes the first = sign in macro declaration by a space. So the parameter:

-D b+=2

is equal to

#define b+ 2

which because gcc has an extension to interpret it like that, it is equal to

#define b + 2

which makes the preprocessor output:

printf("%d\n", 2 + 2 | ~ 2 + 2);

the expression 2 + 2 | ~ 2 + 2 is equal to (2 + 2) | ((~ 2) + 2) (see operator precedence) which on twos complement system is equal to 4 | (-3 + 2) which is equal to 4 | -1. On twos-complement -1 is equal to 0xff....ff so 4 | -1 is equal to 0xff...ff (as it is binary OR) which is -1.

Upvotes: 7

bruno
bruno

Reputation: 32596

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;
}

Upvotes: 4

Related Questions