如何通过值调用和通过引用调用在C中工作?

Nim*_*ekh 2 c c++

在C程序中,函数调用如何工作,以及如何通过引用调用,以及如何返回值?

Tom*_*Tom 12

按价值呼叫

void foo(int c){
    c=5; //5 is assigned to a copy of c
}
Run Code Online (Sandbox Code Playgroud)

像这样称呼它:

int c=4;
foo(c);
//c is still 4 here.
Run Code Online (Sandbox Code Playgroud)

通过引用调用:传递指针.引用存在于c ++中

void foo(int* c){
    *c=5; //5 is assigned to  c
}
Run Code Online (Sandbox Code Playgroud)

像这样称呼它:

int c=0;
foo(&c);
//c is 5 here.
Run Code Online (Sandbox Code Playgroud)

返回值

int foo(){
    int c=4;
     return c;//A copy of C is returned
}
Run Code Online (Sandbox Code Playgroud)

通过参数返回

   int foo(int* errcode){

       *errcode = OK;

        return some_calculation
   }
Run Code Online (Sandbox Code Playgroud)


Dan*_*den 5

C语言不支持call-by-reference.

你可以做的是传递一个指针(它作为一个参考,但与C++称之为"引用"的不同)传递给你的函数感兴趣的数据,这使你能够完成大多数调用的事情.参考是有益的.

  • @caf:在你的陈述中,你是完全正确的.另外,"引用调用"是一个不同的东西,其含义与C++语言的通用"引用"概念相比更类似于C++的引用.call-by-reference引入了特定的语义功能,其中最重要的是callees可以在调用者的上下文中重新绑定变量.传递指针*不是*相同,因为被调用者可以改变指向对象,但不能重新绑定调用者的指针指向其他东西. (2认同)