Today I tried to use const indentifier, but I find the const variable can still be modified, which confuses me..
Following is the code, in compare(const void *a, const void *b) function, I tried to modify the value that a is pointing to:
#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;
}
Then I also tried to change the value of a itself:
#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;
}
However, I found both of them works..
Can anyone explain to me why I need to use const in the parameter list of compare if they can still be changed?
Case 1: You are using a static cast to cast away the constness. You are violating the contract that was defined for the method.
Case 2: You are not changing the contents of a (which is const), but assigning the variable a which contains a const void pointer.
For practical implications: With case 1.) you could shoot yourself in the foot, in case a was not really pointing to a variable.
Suggestion: Cast away constness only if you know what you are doing.