为什么我的价值由C中传递函数的参数? [英] Why would I pass function parameters by value in C?
问题描述
我除尘我的C技能对我的一些C库工作。有拼凑第一工作实施后,我现在要在code,使之更有效率。目前我通过引用或值传递函数参数的话题。
I am dusting off my C skills working on some C libraries of mine. After having put together a first working implementation I am now going over the code to make it more efficient. Currently I am on the topic of passing function parameters by reference or value.
我的问题是,为什么我会永远用C按值传递的函数参数?在code看起来干净,但不会总是少效率比通过引用传递?
My question is, why would I ever pass any function parameter by value in C? The code might look cleaner, but wouldn't it always be less efficient than passing by reference?
推荐答案
在C,所有的参数都是按值传递。一个真正的通过引用传递是当你看到修改的效果没有任何明确的间接可言:
In C, all arguments are passed by value. A true pass by reference is when you see the effect of a modification without any explicit indirection at all:
void f(int c, int *p) {
c++; // in C you can't change the original paramenter passed like this
p++; // or this
}
使用值,而不是指针虽然经常需要:
Using values instead of pointers though, is frequently desirable:
int sum(int a, int b) {
return a + b;
}
您不会写这样的:
int sum(int *a, int *b) {
return *a + *b;
}
由于它是不是安全,这是低效率的。低效的,因为有一个附加的间接。此外,在C,指针参数表明的值将通过指针修改的调用者(尤其如此,当尖类型具有小于或等于指针本身的尺寸)。
Because it is not safe and it is inefficient. Inefficient because there is an additional indirection. Moreover, in C, a pointer argument suggests the caller that the value will be modified through the pointer (especially true when the pointed type has a size less than or equal to the pointer itself).
这篇关于为什么我的价值由C中传递函数的参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!