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

后端 未结 8 1641
暖寄归人
暖寄归人 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:49

    In languages which support pass-by-reference, there exists a means by which a function can be given something that can be used to identify a variable know to the caller until the called function returns, but which can only be stored in places that won't exist after that. Consequently, the caller can know that anything that will be done with a variable as a result of passing some function a reference to it will have been done by the time the function returns.

    Compare the C and C# programs:

    // C               // C#
    int x=0;           int x=0;
    foo(&x);           foo(ref x);
    x++;               x++;
    bar();             bar();
    x++;               x++;
    boz(x);            boz(x);
    

    The C compiler has no way of knowing whether "bar" might change x, because foo() received an unrestricted pointer to it. By contrast, the C# compiler knows that bar() can't possibly change x, since foo() only receives a temporary reference (called a "byref" in .NET terminology) to it and there is no way for any copy of that byref to survive past the point where foo() returns.

    Passing pointers to things allows code to do the same things that can be done with pass-by-ref semantics, but pass-by-ref semantics make it possible for code to offer stronger guarantees about things it won't do.

提交回复
热议问题