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

前端 未结 2 1755
伪装坚强ぢ
伪装坚强ぢ 2020-12-15 00:04

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 referen

相关标签:
2条回答
  • 2020-12-15 00:24

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

    0 讨论(0)
  • 2020-12-15 00:38

    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)
    
    0 讨论(0)
提交回复
热议问题