Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using const with a pointer in c

I don't understand why the following code works

typedef struct {
double x;
double y;
double z;
} abc;

static void test(abc const* b)
{
    (void)memset((void *)&(b->x), 0, sizeof(double));
}

int main(int argc, char *argv[])
{
    abc blah = {11, 12, 23};

    printf("\n%f - %f - %f\n", blah.x, blah.y, blah.z);
    test(&blah);
    printf("\n%f - %f - %f\n", blah.x, blah.y, blah.z);
    while (1);
}

In the function test, I have set b as a pointer pointing to a const value. And yet I'm able to change the value of x.

like image 759
JJT Avatar asked Nov 30 '25 02:11

JJT


1 Answers

You are using a cast to hack away the const-context of the pointer passed into test, so your operation is permitted at compilation.

blah.x is in fact mutable, so there's nothing undefined about this. It's just really poor style.

Your program's behaviour would be undefined if the object itself were const:

[C99: 6.7.3/5]: If an attempt is made to modify an object defined with a const-qualified type through use of an lvalue with non-const-qualified type, the behavior is undefined. If an attempt is made to refer to an object defined with a volatile-qualified type through use of an lvalue with non-volatile-qualified type, the behavior is undefined.

However, creating a const-qualified handle to that object doesn't make the object const; it only means you are prevented (at compile-time) from mutating it through that handle, unless you hack away the constness as you have done here.

like image 104
Lightness Races in Orbit Avatar answered Dec 02 '25 17:12

Lightness Races in Orbit



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!