[英]Function comparing integers in C (pointers)
Here's the following function which is supposed to compare the values of two integers a
and b
and return a positive number if a>b
and a negative number otherwise: 下面的函数应该比较两个整数a
和b
的值,如果a>b
则返回一个正数,否则返回一个负数:
int int_cmp(const void *a, const void *b)
{
const int *ia = (const int*)a;
const int *ib = (const int*)b;
return *ia - *ib;
}
I am not too familiar with constant
pointers (or pointers to constant
s) and I do not really understand the reasoning behind the function above. 我对constant
指针(或指向constant
s的指针)不太熟悉,并且我不太了解上面函数的背后原因。 I would appreciate it if someone could provide a step-by-step explanation. 如果有人可以提供分步说明,我将不胜感激。
suppose, in the caller function, you have two int variables, 假设在调用者函数中,您有两个int变量,
int p = 10;
int q = 5;
now , from your main()
you are calling int_cmp(&p, &q);
现在,从main()
您正在调用int_cmp(&p, &q);
to compare their values. 比较他们的价值观。
in the receiving function int_cmp()
the parameters are made const
so that inside the int_cmp()
function, the values of int p
and int q
should not be changed. 在接收函数int_cmp()
中将参数设置为const
以便在int_cmp()
函数内部不更改int p
和int q
的值。 If the values of a
and/or b
is changed in the int_cmp()
, they will be changed in the main()
also, as they have been passed using reference. 如果a
和/或b
的值在int_cmp()
中更改,则它们也将在main()
更改,因为它们已使用引用传递。 so, to keep the values unchanged, the const
is used. 因此,为了保持值不变,将使用const
。
Next, once the parameters are received in int_cmp()
, they are typecasted to int
as the arithmetic operators can be safely allowed on pointers of defined variable type. 接下来,一旦在int_cmp()
中接收到参数, int_cmp()
它们类型转换为int
因为可以安全地在定义的变量类型的指针上允许算术运算符。
I hope the atithmatic part is quite straightforward. 我希望算术部分很简单。 It is de-referencing the pointers and calculating the difference between the values of the pointers a
and b
and returning the value of the difference. 它取消对指针的引用,并计算指针a
和b
的值之间的差,并返回差的值。
I'm guessing this method is used in more general callback that expects a function pointer of the following type 我猜想这种方法用在更通用的回调中,期望使用以下类型的函数指针
int (*)(const void*, const void*)
This is the only reason I can see to use const void*
here instead of const int*
. 这是我可以看到在这里使用const void*
而不是const int*
的唯一原因。
The reason for const is that comparison should be an operation that reads data only. 使用const的原因是比较应该是仅读取数据的操作。 It shouldn't have any need to mutate the parameters in order to compare them. 它不需要对参数进行任何突变即可进行比较。 Hence the standard definition of compare takes const
data to encourage implementers to have the correct behavior 因此,compare的标准定义采用const
数据来鼓励实施者采取正确的行为
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.