Praveen
Praveen

Reputation: 9335

macro and unexpected result in c++

I couldn't find a proper title for this question, sorry for that;

I found below piece of code in a blog

#include <iostream>

#define TEN 10;
#define EIGHT TEN-2; 

int main() {
    int size = EIGHT;
    std::cout << size;
}

Out Put: 10

Why is it 10 not 8?

Upvotes: 1

Views: 125

Answers (2)

VP.
VP.

Reputation: 16705

  1. Evaluations of expressions in #define should be covered with parentheses:

    #define EIGHT (TEN - 2)
    
  2. From N4296.

    A preprocessing directive of the form:

    #define identifier replacement-list new-line 
    

    defines an object-like macro that causes each subsequent instance of the macro name to be replaced by the replacement list of preprocessing tokens that constitute the remainder of the directive.

So no any ; is needed, as @TartanLlama pointed. That is caused your problem.

Upvotes: 1

TartanLlama
TartanLlama

Reputation: 65610

Macros are directives to the preprocessor, not C++ statements. They don't need to be terminated with a semicolon, they just do substitution on tokens.

Your code expands to this:

int main() {
    int size = 10;-2;;
    std::cout << size;
}

Note that the semicolons have been substituted in. The simple fix is to change your macros:

#define TEN 10
#define EIGHT TEN-2

However, you should use const int instead of macros for constants like that to avoid issues like the one you just came across.

Upvotes: 4

Related Questions