-3

Why this code:

#include <iostream>
#define DIFF(x,y) x-y

int main()
{
    std::cout <<   DIFF(5,3) << std::endl;
    std::cout << 1*DIFF(5,3) << std::endl;
    std::cout << 2*DIFF(5,3) << std::endl;
    std::cout << 3*DIFF(5,3) << std::endl;
    std::cout << 4*DIFF(5,3) << std::endl;
    std::cout << 5*DIFF(5,3) << std::endl;
    std::cout << 6*DIFF(5,3) << std::endl;
    std::cout << 7*DIFF(5,3) << std::endl;
    std::cout << 8*DIFF(5,3) << std::endl;
    std::cout << 9*DIFF(5,3) << std::endl;
    
    return 0;
}

has that output? 2 2 7 12 17 22 27 32 37 42

I cannot undestand what is happening inside and cant find documentation about it

Boski
  • 1

1 Answers1

0

DIFF is a c preprocessor definition. The c preprocessor is a text processor that doesn't know anything about c. It basically copy-pastes the definition of DIFF into the code before compilation. That means that

    std::cout << 2*DIFF(5,3) << std::endl;

becomes

    std::cout << 2*5-3 << std::endl;

Which is 10-3 = 7

To solve this you could add parentheses like (x-y) in your define.

Or, since you are using c++, you might want to use a consterxpr function like this:

constexrpr int DIFF(int x,int y){ return x-y;} 

which has the advantage of type safety, and namespace scoping etc.

David van rijn
  • 2,108
  • 9
  • 21