-2
#define BLUR 2
#define LEN (2 * BLUR + 1) * (2 * BLUR + 1)

using namespace std;
int main()
{
    cout << 50 / LEN; // result is 50
}

the expected result is 2 but it's 50. I try another numbers but get the wrong answer. with other operation like *, + and - the output is valid but not with division.

8
  • 4
    Try to expand the macros on a paper with a pencil. Commented Jun 28, 2024 at 3:19
  • 5
    Since you're using C++, you should use const or constexpr variables instead. Commented Jun 28, 2024 at 3:22
  • 4
    @3CxEZiVlQ is right. Remember that LEN isn't 25; it's (2 * BLUR + 1) * (2 * BLUR + 1). Commented Jun 28, 2024 at 3:29
  • 3
    Your title says "#define numbers", which I would expect to mean something like #define 25. What you have is more of a "#define expression". Commented Jun 28, 2024 at 3:38
  • Welcome to Stack Overflow. Further to what the others have stated, consider what the order of operations is. Commented Jun 28, 2024 at 3:38

1 Answer 1

7

LEN expands to (2 * 2 + 1) * (2 * 2 + 1), so your expression expands to

50 / (2 * 2 + 1) * (2 * 2 + 1)

In C++, division and multiplication have the same precedence, and associate left to right - effectively giving the same order of operations as in ordinary paper-and-pencil arithmetic. So the division gets evaluated before the outer multiplication. You are computing

(50 / (2 * 2 + 1)) * (2 * 2 + 1)

which is indeed 50.

Just because some tokens came from expanding a macro, does not automatically make them grouped into a single expression. When you want this, you have to include parentheses in the definition. So change your macro definition to

#define LEN ((2 * BLUR + 1) * (2 * BLUR + 1))

However, in modern C++ it is better to use a constexpr variable, and in that case the issue doesn't arise.

constexpr int BLUR = 2;
constexpr int LEN = (2 * BLUR + 1) * (2 * BLUR + 1);

will work as expected.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.