7

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.

Community
  • 1
  • 1
SundayMonday
  • 19,147
  • 29
  • 100
  • 154

4 Answers4

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

DrummerB
  • 39,814
  • 12
  • 105
  • 142
2

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

Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331
2

There are differences:

  1. Define is textual substitution:

    • Define is preprocessor textual substitution made before compilation. You will achieve the same effect when you textually replace 5 in every occurrence of define.
  2. Static const is a variable in memory

    • Static const however is an instance of NSInteger type that resides in program memory. You cannot change it during runtime, but it is a value which is present in the memory and its own address as a variable.
pro_metedor
  • 1,176
  • 10
  • 17
1

#define myInteger 5 is a macro that declares a constant.

So wherever you use myInteger macro it gets replaced with 5 by the preprocessor engine.

const NSInteger myInteger = 5; declares a variable myInteger that holds the value 5.

But their usage is the same, that is they are constants that can be used to prevent hard coding.

Lews Therin
  • 10,907
  • 4
  • 48
  • 72
  • they are not semantically the same. One is a text find and replace done by the compiler and one is a living breathing runtime memory allocation. – deleted_user Oct 20 '12 at 17:17
  • Wrong terminology used there.. corrected. – Lews Therin Oct 20 '12 at 17:20
  • @deleted_user - You are right, they are not semantically the same, but the `const` object is just that: an object or symbol, but it doesn't necessarily correspond to a "memory allocation" - There might be no actual memory allocated since it might be inlined or otherwise optimized. – Mark Lakata Sep 24 '13 at 20:14