Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can I modify the const pointer in C?

Tags:

c

pointers

memory

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?

like image 988
Hanfei Sun Avatar asked Dec 17 '22 00:12

Hanfei Sun


2 Answers

It only works in this case because the pointer you're working against wasn't originally constant. Casting away constness and then modifying a value is undefined behaviour. UB means that the app can do anything from succeed to crash to make purple dragons fly out of your nostrils.

like image 133
Jonathan Grynspan Avatar answered Dec 21 '22 22:12

Jonathan Grynspan


Its protecting you from silly mistakes, not when you try hard to make a mistake.
(int *)a when a is const something * is a bad practice, use (const int *)a instead.
a = b when a is const void * is ok because only the value pointed to is const. if you want both *a = x and a = x disallowed, declare a as const void * const.

like image 21
Dani Avatar answered Dec 21 '22 23:12

Dani