kyrpav
kyrpav

Reputation: 778

Using #define macros in a simple cout expression

I would like to ask why this code prints out 2 instead of 0. Doesn't #define "assign" values to the names of the macros and calculate also the result? How does it give this answer?

#include <iostream>
using namespace std;

#define A    0
#define B    A+1
#define C    1-B

int main() {
    cout << C<<endl;
    return 0;
}

Upvotes: 0

Views: 329

Answers (3)

MooseBoys
MooseBoys

Reputation: 6793

The preprocessor expands the C macro to 1-B, which expands to 1-A+1 which expands to 1-0+1 which equals 2. Don't think of it in terms of sequential assignment, but you can get the desired behavior by adding parenthesis around the macro definitions. Then the C macro would expand to (1-B), then (1-(A+1)) then (1-((0)+1)) which equals 0.

Edit:

As an example, the code snip below prints 42, even though BAR is "assigned" to FOO when FOO equals 17. This is because the expansion is deferred until it's actually used. On the cout line, BAR is still equal to FOO, but at that point, FOO is now 42, not 17. Note that it's bad practice to redefine a macro without first #undefining it.

#define FOO 17
#define BAR FOO
#define FOO 42
cout << BAR << endl;

Upvotes: 2

NathanOliver
NathanOliver

Reputation: 180945

Macros are direct text replacements That means

#define C    1-B

becomes

1-A+1

and then A gets expanded so we have

1-0+1

which is 2. If you want 0 then stop using macros and instead use constant variables

const int A = 0;
const int B = A + 1;
const int C = 1 - B;

And now C is 0.

Upvotes: 3

Frank Puffer
Frank Puffer

Reputation: 8215

Because C expands to 1-0+1

Preprocessor defines simply replace text and don't care about operator precedence or calculation rules.

Upvotes: 0

Related Questions