# constant string literals

This topic is 3404 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

Is there an option in Visual Studio 2008 to define string literals as being const char[] instead of just char[] ?

##### Share on other sites
They are constant as defined by the standard and changing the string is undefined. You can add the const if you feel so inclined, if this is because you are trying to change the values then I think you have a bigger problem.

##### Share on other sites
I simply want things like the following to be a compile time error:
#include <stdio.h>#include <string.h>int main(void){    char test[20];    strcpy("Hello World", test); // whoops, accidentally swapped the parameters    return 0;}

##### Share on other sites
As far as I know there is no option as it may work correctly yet it also may start a sequence which results in the end of the world. If there was such an option in VS then the msdn page would mention it.
Quote:
 if this is because you are trying to change the values then I think you have a bigger problem.

##### Share on other sites
Quote:
 Original post by dmailif this is because you are trying to change the values then I think you have a bigger problem.

I don't. I want to teach students the difference between
char a[] = "Hello World";char *b = "Hello World";

And I would just like the compiler to complain about the second line. Conceptually, string literals are constant. So why not enfore this and make them const?

##### Share on other sites
Welcome to the unhappy world of C compatibility features.

##### Share on other sites
Quote:
 Original post by SiCraneWelcome to the unhappy world of C compatibility features.
That about sums it up.
I don't know if any compilers have flags that will make them const, but it seems like it would be a nice feature.

##### Share on other sites
Quote:
Original post by iMalc
Quote:
 Original post by SiCraneWelcome to the unhappy world of C compatibility features.
That about sums it up.
I don't know if any compilers have flags that will make them const, but it seems like it would be a nice feature.

In gcc, -Wwrite-strings will issue a warning if you try to use a string literal as non-const.

#include <stdio.h>int main() {  char *s = "Hello, world!\n";  printf(s);    return 0;}

kk.c: In function 'main':kk.c:4: warning: initialization discards qualifiers from pointer target type

##### Share on other sites
Quote:
 Original post by alvaroIn gcc, -Wwrite-strings will issue a warning if you try to use a string literal as non-const.

That's exactly what I was looking for, but unfortunately, my students are using VS 2008 and not gcc :(

##### Share on other sites
Turning on string pooling should allow you to illustrate the issue, using code something like this:

char *s1 = "Hello World";char *s2 = "Hello World";strcpy(s1, "Whatever");printf(s2);