今天我尝试使用const标识符,但我发现const变量仍然可以修改,这让我感到困惑.
以下是代码,在compare(const void*a,const void*b)函数中,我试图修改a指向的值:
#include <stdio.h>
#include <stdlib.h>
int values[] = {40, 10, 100, 90, 20, 25};
int compare (const void *a, const void*b)
{
*(int*)a=2;
/* Then the value that a points to will be changed! */
return ( *(int*)a - *(int*)b);
}
int main ()
{
int n;
qsort(values, 6, sizeof(int), compare);
for (n = 0; n < 6; n++)
printf("%d ", values[n]);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
然后,我还试图改变的价值一个本身:
#include <stdio.h>
#include <stdlib.h>
int values[] = {40, 10, 100, 90, 20, 25};
int compare (const void *a, const void*b)
{
a=b;
return ( *(int*)a - *(int*)b);
}
int main ()
{
int n;
qsort(values, 6, sizeof(int), compare);
for (n = 0; n < 6; n++)
printf("%d ", values[n]);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
但是,我发现它们都有效.任何人都可以向我解释为什么我需要在比较参数列表中使用const,如果它们仍然可以更改?
它只适用于这种情况,因为你正在使用的指针最初不是常数.抛弃const然后修改值是未定义的行为.UB意味着应用程序可以做任何事情,从成功到崩溃,让紫色的龙飞出你的鼻孔.