2

Does multiple #define of the same string use the same constant string? Say I do the following in multiple places:

#define TEST @"test"

Compiler is smart enough to know it refers to the same constant string in the data section right?

AstroCB
  • 12,337
  • 20
  • 57
  • 73
Boon
  • 40,656
  • 60
  • 209
  • 315

2 Answers2

2

Truly your question does not have much to do with what #define does, but rather about how string literals are treated by the compiler. The compiler inserts the string object into the program image, which is read-only and doesn't implement the retain count. This is an optimization so that the string doesn't need to be created at runtime.

Usually the compiler is enough smart to recognize that you are using the same string literal, and the same constant string will be used, but it will not be in the heap.

Also check this question: Authoritative description of ObjectiveC string literals?

Community
  • 1
  • 1
Ramy Al Zuhouri
  • 21,580
  • 26
  • 105
  • 187
1

The compiler does something called string interning. It is not a necessary operation so if your code relies on test being at the same address then you may have some problems. For the most part yes, it will try to reuse strings that are the same and just make them all point to the same string (in read only memory).

Jesus Ramos
  • 22,940
  • 10
  • 58
  • 88