How do #defines work in Objective-C?
I have a background in C/C++ and am now trying to pick up Objective-C. #defines don't seem to work in objective-c the same way they work in c and C++, where the compiler just replaces all references to the defines with what they are supposed to represent.
When I try to u开发者_运维问答se #defines in Objective-C they only work sometimes. Like when I do something like this;
#define NUMBER 5
int myArray[NUMBER];
I get compiler errors saying there is a square bracket missing, where if I use this line instead it works fine;
int myArray[5];
Surely these should both be the same thing?
Also if I try to use #define value in any sort of equations I get similar sort of compiler errors. This code wont work;
#define NUMBER 5
float var = NUMBER * 0.2;
Where as this is fine;
float var = 5 * 0.2;
Anyone any idea why this might be, or how #defines are handled differently by the Objective-C compiler. I'm using XCode by the way, just incase that makes a difference.
#define
in Objective-C works exactly the same way it works in C. All of your examples work fine for me in a quick test I tried. It's likely you have some other problem which is making the errors you're seeing - can you post your actual code and the text of your error messages?
I've normally seen problems like that when I have an accidental semicolon in the #define
.
To figure out the behavior of your #defines, I would suggest using Xcode's Build->Preprocess command to see exactly what text the preprocessor is generating for you.
精彩评论