【发布时间】:2012-05-04 21:07:27
【问题描述】:
今天我尝试使用 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;
}
然后我也尝试改变a本身的值:
#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;
}
但是,我发现它们都有效.. 谁能向我解释为什么我需要在 compare 的参数列表中使用 const 如果它们仍然可以更改?
【问题讨论】:
-
你把 const 扔掉了。改为转换为
const int*。 -
引用我自己的话:(im)mutability 是对象本身的固有属性,与用于访问它的指针的限定无关 - 因为
values不是tconst-qualified,修改它是完全合法的......