views:

46

answers:

2

How do #defines work in objective-c? I have a background in C/C++ and am now trying to pick up objecive-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 use #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.

+5  A: 

#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?

Carl Norum
Its a big project the #defines in use are in different files to where I want to use them, I would probably have to put up the whole project to find it. I must just be doing something silly, ill figure it out. At least now I know for sure it works the same as in C, thanks.
Tiddly
A: 

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.

Jay O'Conor