xorl %eax, %eax

Fun with Constant Values in C

with one comment

Everyone that knows the essentials of C programming is capable of understanding that the following code cannot compile since it is changing a read-only (constant) variable. The concept is simple:

#include <stdio.h>

int
main(void)
{
   const int val = 1;
   val = 2;
   printf("%d\n", val);
   return 0;
}

Which of course generates this error on compile time:

sh-3.2$ gcc con.c -o con
con.c: In function ‘main’:
con.c:7: error: assignment of read-only variable ‘val’
sh-3.2$

But is there a way to change a read-only variable inside a program in a legit fashion? Definitely, remember.. everything is just bits and bytes on memory, pointers and data types make them start and end at certain ranges so.. You can easily make a pointer to the address of integer val and then change the data located at this address. This way the contents of the variable will be changed in a completely legal manner without even ‘touching‘ it directly. Here is the proof of the above speculation:

#include <stdio.h>

int
main(void)
{
   const int val = 1;

   int *ptr = (int *) &val;
   *ptr = 42;

   printf("%d\n", val);
   return 0;
}

As you can see, ptr contains the address of val, next the data that this pointer points to gets changed to the value of 42. Presumably this method works in the most legit way but on the other hand it’s ‘breaking the rules‘ since it manipulates read-only variables. Here is the above code on runtime:

sh-3.2$ gcc con1.c -o con1
sh-3.2$ ./con1
42
sh-3.2$

Just a funny and useful(?) C programming nuance in my humble opinion.

Written by xorl

January 7, 2009 at 13:55

Posted in C programming

One Response

Subscribe to comments with RSS.

  1. I never think like this friend..
    you are great..

    ti88

    December 30, 2009 at 05:32


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s