0

I am trying C++, There is a point about can not understanding about #define addition. The example code below.

#include <iostream>

using namespace std;

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


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

The result gives A -> 0, B -> 1, C-> 4. How C equal 4 ?

PALES
  • 7
  • 2

2 Answers2

1

#define performs simple textual substitution. When you expand B out, you get 0+1 in source code, which is not necessarily identical to "an integer with the value 1".

So, in your example code, if we substitute the values in:

int main(){
    cout << 0 << endl;
    cout << 0+1 << endl;
    cout << 3-0+1;
    return 0;
} 

3 - 0 + 1 is 4.

Nathan Pierson
  • 5,461
  • 1
  • 12
  • 30
0

Do the text substitution. B expands to 0+1. C expands to 3-0+1 rather than 3-1.

cout << C;

Becomes:

cout << 3-0+1;

Because of order of operations this displays 4 rather than 2.

An easy way to see this would be to try something like:

cout << C * 50;

If we operate under the faulty assumption that C is actually 4, we'd expect to see 200. But because the above is equivalent to:

cout << 3-0+1 * 50;

Then we correctly see 53.

Chris
  • 26,361
  • 5
  • 21
  • 42