开发者

How does the const keyword differ between iPhone and .NET?

开发者 https://www.devze.com 2023-01-29 12:56 出处:网络
I\'m a .NET developer coming to the iPhone, I\'m still feeling my way around at the moment. I\'ve hit a point at which in .NET I\'d normally use a named constant for readability.

I'm a .NET developer coming to the iPhone, I'm still feeling my way around at the moment.

I've hit a point at which in .NET I'd normally use a named constant for readability. I understand there's a const keyword in iPhone dev too but most examples I've seen use a #define in this instance.

What are the real differences betwe开发者_StackOverflow社区en the two implementations? Bonus question: How and when should they / shouldn't they be used?


There are a number of other question on SO that discuss how constants are declared and behave in Objective-C, you should look at the following:

Constants in Objective-C

Objective-C “const” question

Significance of const keyword positioning in variable declarations

To compare and contrast against C#, I would point out that const in Obj-C is essentially the same as it is in the C language (Obj-C is a superset of C in fact). In Obj-C, constants are declared at the global scope and must be initialized to a value known at compile time. Objective-C does not support constants as class members. In C# constants are always members of a class (or struct) and must also be initialized using a value known at compile time. C# #define does not allow a value to be associated with a defined symbol, rather it is used to allow conditional compilation paths to be chosen (using #if and #else), which is quite different.

With regard to using #define to declare constants, I personally try to avoid this when possible. Values that are #defined are simply substituted into code at compile time - and could be interpreted differently in different contexts. It's also possible to introduce name collisions which could result in redefinitions of a value unexpectedly. My suggestions is to use const when you can and #define only when you must.


#defines are preprocessor macros that are replaced in the final code. As such, they have a once defined value and can be accessed at no cost. const on the other hand just statically allocates a variable that the compiler handles. As such, I would (or rather am) using #define rather than const for most tasks.
Only #defined'd constants can be used for switch statments, btw.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号