Mailing Lists: Apple Mailing Lists

Image of Mac OS face in stamp
 
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Interesting preprocessor code behavior



Hi all,

I'm not sure this really belongs in an Xcode list, or if it's more of a general gcc (or even C++) item. But I thought you might like to hear about this, in case you weren't aware or hadn't seen such a thing before.

Preprocessor comparisons (like #if (A==B)) cannot be relied upon to consistently pass OR fail if either symbol is undefined.

I had preprocessor code which compared one #define'd symbol against others in an #if/#elif/#endif block, to determine which type of setup we were compiling for (mono, stereo or surround, specifically). A co- worker inserted in the middle of that a new #elif comparison against a newly #define'd symbol (one which I was not aware of and had not added to my own headers yet). When compiling my code, the comparison against this undefined symbol apparently evaluated as true, causing my code to compile with completely incorrect settings, leading to apparently random behavior and crashes. It was a quite, well, interesting problem to track down.

So, my point is: in preprocessor code, a comparison between symbols MAY evaluate as either true OR false when one of the symbols is undefined, regardless of the value of the other symbol. The compiler won't produce an error (as it will in the regular C++ code), and you cannot assume any undefined symbol has a value of 0 (or *any* specific value, for that matter). Thus, you cannot make any assumption about whether the comparison will pass or fail.

This is why I generally prefer to use #ifdef SYMBOL instead of #if (SYMBOL==1) for simple flag-like symbols, just so I don't have to remember to #define SYMBOL 0 for the cases where I want the #if to fail. If I use the comparison method, and forget to define the symbol as 0, it may PASS the comparison!

Ok, maybe you knew this already, but I thought it might be helpful to pass on, just in case...

-Howard

_______________________________________________
Do not post admin requests to the list. They will be ignored.
Xcode-users mailing list      (email@hidden)
Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/xcode-users/email@hidden

This email sent to email@hidden


Visit the Apple Store online or at retail locations.
1-800-MY-APPLE

Contact Apple | Terms of Use | Privacy Policy

Copyright © 2007 Apple Inc. All rights reserved.