Possible Duplicate:
“static const” vs “#define” in C
In Objective-C what is the difference between the following two lines:
#define myInteger 5
static const NSInteger myInteger = 5;
Assume they're in MyClass.m above the implementation directive.
The first, const, is initialized during compile-time and the latter, readonly, initialized is by the latest run-time. The second difference is that readonly can only be initialized at the class-level. Another important difference is that const variables can be referenced through "ClassName.
const is a constant value, and cannot be changed. It is compiled into the assembly. static means that it is a value not related to an instance, and it can be changed at run-time (since it isn't readonly ). So if the values are never changed, use consts.
Constant is just a constant, i.e. you can't change its value after declaring. Static variable is accessible without making an instance of a class and therefore shared between all the instances of a class.
They mean exactly the same thing. You're free to choose whichever you think is easier to read. In C, you should place static at the start, but it's not yet required.
#define myInteger 5
is a preprocessor macro. The preprocessor will replace every occurrence of myInteger
with 5
before the compiler is started. It's not a variable, it's just sort of an automatic find-and-replace mechanism.
static const NSInteger myInteger = 5;
This is a "real" variable that is constant (can't be changed after declaration). Static means that it will be a shared variable across multiple calls to that block.
When using #define the identifier gets replaced by the specified value by the compiler, before the code is turned into binary. This means that the compiler makes the substitution when you compile the application.
When you use const and the application runs, memory is allocated for the constant and the value gets replaced when the applicaton is ran.
Please refer this link:- Difference between static const and #define
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With