views:

326

answers:

7

Deep down in WinDef.h there's this relic from the segmented memory era:

#define far
#define near

This obviously causes problems if you attempt to use near or near as variable names. Any clean workarounds? Other then renaming my variables?

+3  A: 

maybe:

#undef near
#undef far

could be dangerous though...

John Boker
Safer in a source file than a header...
Steve Jessop
+2  A: 

Best not to. They are defined for backwards compatibility with older code - if you got rid of them somehow and then later needed to use some of that old code you'd be broken.

1800 INFORMATION
+5  A: 

Undefine any macros you don't want after including windows.h:

#include <windows.h>
#undef near
#undef far
John Millikin
A: 

You probably don't want to undefined near and far everywhere. But when you need to use the variable names, you can use the following to undefine the macro locally and add it back when you are done.

#pragma push_macro("near")
#undef near
//your code here.
#pragma pop_macro ("near")
Aaron Fischer
A: 

I agree with the other posters that the danger level is high with undef'ing them. If you are dead set on doing that though, you could try digging through the output of the pre-processor (i.e. gcc -E, don't know for VS) to see if anything other than your code is using those names.

Dana the Sane
A: 

One might argue that "near" and "far" are not very descriptive variable names. Have you considered simply providing additional detail in your variable name to resolve the conflict (i.e. nearest_match, furthest_match). Just a thought.

Steve Hawkins
+11  A: 

You can safely undefine them, contrary to claims from others. The reason is that they're just macros's. They only affect the preprocessor between their definition and their undefinition. In your case, that will be from early in windows.h to the last line of windows.h. If you need extra windows headers, you'd include them after windows.h and before the #undef. In your code, the preprocessor will simply leave the symbols unchanged, as intended.

The comment about older code is irrelevant. That code will be in a separate library, compiled independently. Only at link time will these be connected, when macros are long gone.

MSalters
+1 for correcting the insanity of most of the other responses.
R..