I'm currently studying global - local variables in C++. From what I understand, we can use the same variable name as global and local variable in the same program (in my program I've used 'g' as the same variable name). However, when I tried to use the same variable name as definition (#define) I got an "expanded from macro 'g' " error. Why is this happening? I thought defined variables work similarly to global variables, is there such a rule that we can't use the same variable name for global and #define at the same time? (My goal was to see if #define was more dominant than global variables).
Please help this newbie out!
Code:
#include <iostream>
#define g 5
using namespace std;
int g = 10;
int main()
{
int g = 20;
cout << g;
return 0;
}
#define
does not define a variable. It defines a macro that is replaced as a sequence of tokens in the rest of the code before any of the code is actually compiled. There is no scope to them.
There is literally a translation step (called the preprocessor) which will replace the g
with 5
everywhere in the rest of the code, so that the program that will be compiled is actually
/* contents from <iostream> here */
using namespace std;
int 5 = 10;
int main()
{
int 5 = 20;
cout << 5;
return 0;
}
I think you can see why that doesn't work.
Use global const
variables instead of #define
to define constants. Preprocessor macros have no relation to variables or scopes.
Compilers also have options to show you the code after the preprocessing phase (instead of going on to the compilation phase). For example for GCC and Clang that would be the -E
command line option. You can see the full output for your program here. (Scroll down to the very bottom on the right pane with the output. All that text before your code are the expanded contents from #include<iostream>
.)