Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between static const and #define in Objective-C [duplicate]

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.

like image 851
SundayMonday Avatar asked Oct 20 '12 17:10

SundayMonday


People also ask

What is the difference between static const and readonly?

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.

What is difference between const and static in C#?

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.

What is difference between static and const in PHP?

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.

Is it static const or const static?

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.


2 Answers

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

like image 86
DrummerB Avatar answered Nov 04 '22 11:11

DrummerB


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

like image 39
Rahul Tripathi Avatar answered Nov 04 '22 11:11

Rahul Tripathi