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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With