![]() |
|
![]() |
|
|
Thread Tools | Display Modes |
|
|
|
|
#1 |
|
Hobbyist Programmer
Join Date: Aug 2005
Posts: 137
Rep Power: 4
![]() |
Are #define allowed inside namespaces?
Hi,
I'm learning about namespaces right now and I was wondering if #define is allowed inside a namespace? If so, can I access the constant with a using declaration? Here's an example: #include <iostream>
namespace my_name {
#define LOOP 10
}
using std::cout;
using std::endl;
int main() {
for(int i = 0; i < my_name::LOOP; i++)
cout << i << endl;
return 0;
}I know this code will not compile on an AIX machine. For some reason the compiler thinks that my_name::LOOP which is the value 10 is a string. |
|
|
|
|
|
#2 |
|
Resident Grouch
![]() ![]() ![]() ![]() ![]() ![]() Join Date: Jun 2005
Posts: 6,453
Rep Power: 10
![]() |
#define is a preprocessing statement. That means the substitution is made before the compiler sees the source. Look at your code in view of that textual substitution.
__________________
Abstraction doesn't make it impossible to write bad code; it makes it possible to write superior code. Contributor's Corner: Grumpy on C++ Exceptions DaWei on Pointers |
|
|
|
|
|
#3 |
|
Programming Guru
![]() Join Date: Jun 2005
Location: Adelaide, South Australia
Posts: 1,260
Rep Power: 5
![]() |
Your source code is fed to the preprocessor (and text substitutions made) before the compiler (the program that understands C++ constructs, such as namespace) sees the code. #define therefore does not respect namespaces. Placing a macro in a namespace makes no difference to its effect, and macros do not exist in namespaces.
In your example. the preprocessor sees my_name::LOOP as a potential name which is something distinct from your macro LOOP. One other consequence of the required behaviour of the preprocessor is that; #include <iostream>
#define LOOP 10
namespace my_name
{
}
int main()
{
std::cout << LOOP << '\n';
}#include <iostream>
namespace my_name
{
#define LOOP 10
}
int main()
{
std::cout << LOOP << '\n';
} |
|
|
|
|
|
#4 |
|
Hobbyist Programmer
Join Date: Aug 2005
Posts: 137
Rep Power: 4
![]() |
Yes, now I see it. Thanks for clearing that up.
![]() |
|
|
|
![]() |
| Bookmarks |
| Currently Active Users Viewing This Thread: 1 (0 members and 1 guests) | |
| Thread Tools | |
| Display Modes | |
|
|