const vs static const in C with GCC

Something I’ve been wondering but have yet to see a good explanation for is if there is a difference between the way GCC handles const and static const.  Now in theory the compiler should handle them the same way but does it?  My web search didn’t really come up with much so I decided to test for myself.

A quick test using GCC 4.7.2:

const.c

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

void test()
{
        const char i[] = "not changed";
        char *j;
        printf("before %s\n", i);

        j = i;

        strcpy(j, "changed");
        printf("after i=%s\n", i);
}

int main()
{
        test();
        test();
}

staticconst.c

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

void test()
{
        static const char i[] = "not changed";
        char *j;
        printf("before %s\n", i);

        j = i;

        strcpy(j, "changed");
        printf("after i=%s\n", i);
}

int main()
{
        test();
        test();
}

How each turns out:

const.c

~$ gcc const.c -o const -g
const.c: In function ‘test’:
const.c:10:4: warning: assignment discards ‘const’ qualifier from pointer target type [enabled by default]
~$ ./const
before not changed
after i=changed
before not changed
after i=changed

Not only can I change the variable, but it resets it at each function call so this means it is reallocating the variable each time.

staticconst.c

~$ gcc staticconst.c -o staticconst -g
staticconst.c: In function ‘test’:
staticconst.c:10:4: warning: assignment discards ‘const’ qualifier from pointer target type [enabled by default]
./staticconst
before not changed
Segmentation fault (core dumped)

gdb shows the following:

Core was generated by `./staticconst’.
Program terminated with signal 11, Segmentation fault.
#0  0x0000000000400534 in test () at staticconst.c:12
12        strcpy(j, “changed”);

As you can see static const is stored somewhere actually read only and being static it is not being reallocated each time the function is called making this version more efficient.

 

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *