constant string literals

Started by
8 comments, last by Adam_42 15 years, 5 months ago
Is there an option in Visual Studio 2008 to define string literals as being const char[] instead of just char[] ?
Advertisement
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.
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;}
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.
Quote:Original post by dmail
if 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?
Welcome to the unhappy world of C compatibility features.
Quote:Original post by SiCrane
Welcome 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 order to understand recursion, you must first understand recursion."
My website dedicated to sorting algorithms
Quote:Original post by iMalc
Quote:Original post by SiCrane
Welcome 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


Quote:Original post by alvaro
In 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 :(
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);

This topic is closed to new replies.

Advertisement