0

I have some code with const void* as below:

#include <stdlib.h>
#include <string.h>
#include <stdio.h>    

int main()
{

    const int p = 10;

    char s[] ="I am newbie";

    const void *vp;
    vp = &p;

    *(int*)vp = 11;
    printf("%i\n", *(int*)vp);

    vp= s;
    printf("%s\n", (char*)vp); 

    return 0;
} 

My question is why const void* vp still be updated? As my understanding, const variable can not be updated directly, is that correct for all types?

Thanhpv
  • 64
  • 1
  • 8
  • Using an intermediate void pointer makes no difference at all, compared to `*(int *)&p = 11;` – M.M Sep 18 '16 at 04:07

1 Answers1

3

You effectively removed the const when you got a pointer to your int, cast the pointer to something without the const, and then changed the value of what that points to.

*(int*)vp = 11;

You can cast a pointer type to any other pointer type.

Modifying a const variable like this is undefined behavior. For example, the compiler might have seen that the variable was const, realized that it could pre-compute what the printf functions would print, and do the substitution at compile time as an optimization. The compiler would be allowed to do this because it thinks the variable is const.

IanPudney
  • 5,941
  • 1
  • 24
  • 39
  • Maybe you should mention about pointer to const too. Anyway, +1 for mentioning about undefined behavior when modifying a const. – DDMC Sep 18 '16 at 04:03