Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is Objective-C pass-by-value or pass-by-reference?

Since we always use pointers to define variables, I was wondering if Objective-C is "pass by value", since like Java, the actual value would be passed by using its reference.

However, since it seems to be built up on top of C, would it have all the functionality of C?

like image 754
gran_profaci Avatar asked Mar 06 '14 01:03

gran_profaci


2 Answers

C does not support pass-by-reference and Objective-C, being a strict superset of C doesn't either.

In C (and Objective-C) you can simulate pass-by-reference by passing a pointer, but it's important to remember that you're still technically passing a value, which happens to be a the value of a pointer.

So, in Objective-C (and C, for the matter) there is no concept of reference as intended in other languages (such as C++ or Java).

This can be confusing, so let me try to be clearer (I'll use plain C, but - again - it doesn't change in Objective-C)

void increment(int *x) {
   *x++;
}

int i = 42;
increment(&i); // <--- this is NOT pass-by-reference.
               //      we're passing the value of a pointer to i

On the other hand in C++ we could do

void increment(int &x) {
   x++;
}

int i = 41;
increment(i); // <--- this IS pass-by-reference
              //      doesn't compile in C (nor in Objective-C)
like image 105
Gabriele Petronella Avatar answered Oct 30 '22 19:10

Gabriele Petronella


It is a strict superset of C. It does the same as C. It's one reason all Objects are actually pointers to structs.

like image 26
uchuugaka Avatar answered Oct 30 '22 21:10

uchuugaka