Passing by reference in C

后端 未结 17 2224
梦如初夏
梦如初夏 2020-11-21 23:26

If C does not support passing a variable by reference, why does this work?

#include 

void f(int *j) {
  (*j)++;
}

int main() {
  int i = 20;         


        
17条回答
  •  忘了有多久
    2020-11-21 23:49

    I think C in fact supports pass by reference.

    Most languages require syntactic sugar to pass by reference instead of value. (C++ for example requires & in the parameter declaration).

    C also requires syntactic sugar for this. It's * in the parameter type declaration and & on the argument. So * and & is the C syntax for pass by reference.

    One could now argue that real pass by reference should only require syntax on the parameter declaration, not on the argument side.

    But now comes C# which does support by reference passing and requires syntactic sugar on both parameter and argument sides.

    The argument that C has no by-ref passing cause the the syntactic elements to express it exhibit the underlying technical implementation is not an argument at all, as this applies more or less to all implementations.

    The only remaining argument is that passing by ref in C is not a monolithic feature but combines two existing features. (Take ref of argument by &, expect ref to type by *.) C# for example does require two syntactic elements, but they can't be used without each other.

    This is obviously a dangerous argument, cause lots of other features in languages are composed of other features. (like string support in C++)

提交回复
热议问题