you cannot pass by reference in C but can use pointers as an alternative
是的,没错.
再详细一点.无论您将什么作为参数传递给c函数,它都只通过值传递.无论是变量的值还是变量的地址.
What makes the difference is what you are sending.
When we pass-by-value we are passing the value of the variable to a function. When we pass-by-reference we are passing an alias of the variable to a function. C can pass a pointer into a function but that is still pass-by-value. It is copying the value of the pointer, the address, into the function.
例如,我们可以看到一些C++代码来理解按值调用和按引用调用之间的真正区别.摘自this网站.
// Program to sort two numbers using call by reference.
// Smallest number is output first.
#include <iostream>
using namespace std;
// Function prototype for call by reference
void swap(float &x, float &y);
int main()
{
float a, b;
cout << "Enter 2 numbers: " << endl;
cin >> a >> b;
if(a>b)
swap(a,b); // This looks just like a call-by-value, but in fact
// it's a call by reference (because of the "&" in the
// function prototype
// Variable a contains value of smallest number
cout << "Sorted numbers: ";
cout << a << " " << b << endl;
return 0;
}
// A function definition for call by reference
// The variables x 和 y will have their values changed.
void swap(float &x, float &y)
// Swaps x 和 y data of calling function
{
float temp;
temp = x;
x = y;
y = temp;
}
在这个C++示例中,使用了reference variable(C中不存在).引用this个网站,
"A reference is an alias, or an alternate name to an existing variable...",
和
"The main use of references is acting as function formal parameters to support pass-by-reference..."
这与使用指针作为函数参数不同,因为,
"A pointer variable (or pointer in short) is basically the same as the other variables, which can store a piece of data. Unlike normal variable which stores a value (such as an int, a double, a char), a pointer stores a memory address."
So, essentially when one is sending address 和 receiving through pointers, one is sending the value only, but when one is sending/receiving a reference variable, one is sending an alias, or a reference.
**UPDATE : 11 November, 2015**
There has been a long debate in the C Chatroom, 和 after reading comments 和 answers to this question, i have realized that there can be another way to look at this question, another perspective that is.
让我们看一些简单的C代码
int i;
int *p = &i;
*p = 123;
In this scenario, one can use the terminology that, p's value is a reference to i. So, if that is the case, then if we send the same pointer (int* p
) to a function, one can argue that, since i
's reference is sent to the function, 和 thus this can be called pass-by-reference.
So, its a matter of terminology 和 way of looking at the scenario.
I would not completely disagree with that argument. But for a person who completely follows the book 和 rules, this would be wrong.
NOTE:更新灵感来自this聊天.