Reputation: 324
I have this code in C++:
#include <string>
#include <iostream>
int const foo = 1;
int const bar = 0;
#define foo bar
#define bar foo
int main()
{
std::cout << foo << std::endl;
std::cout << bar << std::endl;
}
It produces this output:
bash-3.2$ ./a.out
1
0
I do not understand why this is the output.
Upvotes: 0
Views: 107
Reputation: 53017
Macros will never expand recursively.
When you write foo
, it first expands to bar
, and then since bar
is a macro it expands back to foo
. While foo
is a macro, because macros can't be recursive it will not be expanded. And then evaluating foo
yields its value: 1.
The same goes for bar
.
See this: http://gcc.gnu.org/onlinedocs/cpp/Self_002dReferential-Macros.html#Self_002dReferential-Macros
And ISO/IEC 14882:2003(E) 16.3.4 Rescanning and further replacement section of the standard. (see comments for more details)
Upvotes: 11