user3050705
user3050705

Reputation: 487

Strange value of the constant multiplication

#include<iostream>
using namespace std;

#define P d2 + 2

int main()
{
    int d2 = 4;

    cout << P * 2;
    getchar();
    return 0;
}

Why this code return 8 instead of 12? When I cout the P, it has 6 value.

Upvotes: 0

Views: 66

Answers (2)

Andrew Stein
Andrew Stein

Reputation: 13170

The C (and C++) preprocessor, which runs before the compiler, does a strict replacement when using directives #include and #define. In other words, after the preprocessor runs, all the compiler sees is

cout << d2 + 2 * 2; 

You should try

#define P (d2 + 2)

or even better avoid macros altogether.

Upvotes: 3

JiaYow
JiaYow

Reputation: 5227

You forget braces. Macros are directly replaced in code. So your statement does:

cout << d2 + 2 * 2

Which is d2 + 4.

Edit your macro to

#define P (d2 + 2)

Upvotes: 1

Related Questions