Passing by reference in C

后端 未结 17 2216
梦如初夏
梦如初夏 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:55

    pointers and references are two different thigngs.

    A couple of things I have not seen mentioned.

    A pointer is the address of something. A pointer can be stored and copied like any other variable. It thus have a size.

    A reference should be seen as an ALIAS of something. It does not have a size and cannot be stored. It MUST reference something, ie. it cannot be null or changed. Well, sometimes the compiler needs to store the reference as a pointer, but that is an implementation detail.

    With references you don't have the issues with pointers, like ownership handling, null checking, de-referencing on use.

提交回复
热议问题