Modifying const variables

This tip submitted by Wiro Sableng on 2006-01-30 01:43:11. It has been viewed 13918 times.
Rating of 5.9 with 104 votes



Warning: you almost never want to do this! But it is useful to know that it is possible--yes, a variable declared const can be modified in a variety of ways. Here is one of them, that demonstrates the power (and danger) of pointers.

int main (void)
{
  /* I assume long is 4 bytes */
  const long num = 0xabcd1234;

  printf("%lx\n", num);
  /* change the first byte */
  ((unsigned char *)&num)[0] = 0xaa;
  printf("%lx\n", num);

  return(0);
}




More tips

Help your fellow programmers! Add a tip!