Are pointers considered a method of calling by reference in C?

后端 未结 8 1628
暖寄归人
暖寄归人 2021-01-30 10:31

In my University\'s C programming class, the professor and subsequent book written by her uses the term call or pass by reference when referring to poin

8条回答
  •  北恋
    北恋 (楼主)
    2021-01-30 10:39

    Does C even have ``pass by reference''?

    Not really.

    Strictly speaking, C always uses pass by value. You can simulate pass by reference yourself, by defining functions which accept pointers and then using the & operator when calling, and the compiler will essentially simulate it for you when you pass an array to a function (by passing a pointer instead, see question 6.4 et al.).

    Another way of looking at it is that if an parameter has type, say, int * then an integer is being passed by reference and a pointer to an integer is being passed by value.

    Fundamentally, C has nothing truly equivalent to formal pass by reference or c++ reference parameters.

    To demonstrate that pointers are passed by value, let's consider an example of number swapping using pointers.

    int main(void)
    {
        int num1 = 5;
        int num2 = 10;
    
        int *pnum1 = &num1;
        int *pnum2 = &num2;
        int ptemp;
    
        printf("Before swap, *Pnum1 = %d and *pnum2 = %d\n", *pnum1, *pnum2);
        temp = pnum1;
        pnum1 = pnum2;
        pnum2 = ptemp;
    
        printf("After swap, *Pnum1 = %d and *pnum2 = %d\n", *pnum1, *pnum2);
    }
    

    Instead of swapping numbers pointers are swapped. Now make a function for the same

    void swap(int *pnum1, int *pnum2)
    {
         int *ptemp = pnum1;
         pnum1 = pnum2;
         pnum2 = temp;
    }
    
    int main(void)
    {
        int num1 = 5;
        int num2 = 10;
    
        int *pnum1 = &num1;
        int *pnum2 = &num2;
    
        printf("Before swap, *pnum1 = %d and *pnum2 = %d\n", *pnum1, *pnum2);
        swap(pnum1, pnum2);
    
        printf("After swap, *pnum1 = %d and *pnum2 = %d\n", *pnum1, *pnum2);
    }
    

    Boom! No swapping!


    Some tutorials mention pointer reference as call by reference which is misleading. See the this answer for the difference between passing by reference and passing by value.

提交回复
热议问题