Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this macro yield 2?

Tags:

c++

macros

I am currently learning the C++ syntax and compilers for my exam.

I was taking a C++ Mock test to prepare for the upcoming exam and I came across a question which asked 'What is the output of the following code?'

#include <iostream>
using namespace std;

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

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

Can someone please explain to me why the code outputs 2 and not 0?

like image 313
Carter Moorse Avatar asked Dec 23 '25 00:12

Carter Moorse


2 Answers

B is expanded to 0+ 1 and C expanded to 1- 0+ 1, which accounts for the result.

It would have been a different matter had you written

#define B    (A+1)

This is a good reason to avoid macros. They are largely unnecessary in C++: templates and constexpr techniques are far better replacements.

like image 104
Bathsheba Avatar answered Dec 24 '25 17:12

Bathsheba


Small addition to @Bathsheba'a answer: if you want to debug such a preprocessor issue, it can be helpful to isolate the interesting part in a standalone file:

// test.cpp

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

C;

and the display the file after preprocessing, e.g. via

g++ -E test.cpp

which gives (on my machine)

# 1 "test.cpp"
# 1 "<built-in>"
# 1 "<command-line>"
# 1 "test.cpp"

1-0 +1;

Note that it's important to remove includes here, e.g. <iostream> makes the output pretty unusable.

like image 42
lubgr Avatar answered Dec 24 '25 16:12

lubgr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!