1

Take the following two forms of creating a string:

const char* pt1 = "Hello";
      char* pt2 = "Goodbye";

What is the use of const in the above? In my understanding, doing:

ptr = "Adios";

Would work for both, since that is changing the address of the pointer, but trying to change a letter in the string would fail for both:

const char* pt1 = "Hello";

compiler error: assignment of read-only location

char* pt2 = "Goodbye";

runtime error: seg fault, trying to change .rodata

Since they produce the same result -- i.e., an error -- is there any advantage in using const when defining a string?

samuelbrody1249
  • 4,379
  • 1
  • 15
  • 58
  • `Since they produce the same output` `compiler error: assignment of read-only location` definitely differs from `runtime error: seg fault, trying to change .rodata`. – KamilCuk Feb 07 '21 at 21:26
  • @KamilCuk -- right, I just mean they both fail. – samuelbrody1249 Feb 07 '21 at 21:26
  • 2
    But when would you like to fail? When you compile your program, or when your client bought your program and you ship your program and it seg faults so you have to do a refund? There is a specific distinction between `compiler error` and `runtime error` - the first is easy to detect and fix. The other one is a program bug and may have disastrous consequences. – KamilCuk Feb 07 '21 at 21:27
  • 1
    @samuelbrody1249 you have to prefix the name of someone other with an @-sign to notify him. – TheEagle Feb 07 '21 at 21:28
  • 1
    @KamilCuk I see, so basically anything you can do to boil the error up to be caught by the compiler is preferable, right? – samuelbrody1249 Feb 07 '21 at 21:30
  • 1
    Yes - static code analysis is _very_ preferable over runtime errors. – KamilCuk Feb 07 '21 at 21:31
  • https://stackoverflow.com/a/45869308/918959 – Antti Haapala -- Слава Україні Feb 07 '21 at 21:36
  • @KamilCuk Correct. Just ask Sony how much they believe the Note 7 fiasco cost them. Lots of zeros in their answer, *I* bet. – Jeff Holt Feb 07 '21 at 21:36
  • It may be, depending on your compiler and machine, faster, as well? – Neil Feb 07 '21 at 21:44

5 Answers5

3

Defining pointers that point to string constants (aka string literals) as const char * allows the compiler to detect an incorrect access if somewhere else in the code you try and modify what pt1 points to as in *pt1 = 'A'; whereas you would just have undefined behavior at runtime if pt1 had type char *, causing a crash on some architectures and less obvious but potentially more damaging side effects on others.

To expand on this subject, there is sometimes a confusion as to the meaning of const for pointer definitions:

const char *pt1 = "Hello"; defines a modifiable pointer pt1 that points to an array of char that cannot be modified through it. Since "Hello" is a string constant, it is the correct type for pt1. pt1 can be modified to point to another string or char, modifiable or not, or be set to NULL.

char *pt2 = "Hello"; defines a modifiable pointer pt2 that points to an array of char that can be modified through it. The C Standard allows this in spite of the constness of "Hello" for compatibility with historical code. gcc and clang can disable this behavior with the -Wwrite-strings command line option. I strongly recommend using this and many more warnings to avoid common mistakes.

const char * const pt3 = "Hello"; defines a constant pointer pt3 that points to an array of char that cannot be modified through it. pt3 cannot be modified to point to another string or even be set to NULL.

char * const pt4 = "Hello"; defines a constant pointer pt4 that points to an array of char that can be modified through it. pt4 cannot be changed once initialized.

char and const can be placed in any order, but whether const is before or after the * makes a big difference.

chqrlie
  • 131,814
  • 10
  • 121
  • 189
1

What is the use of const in the above?

const char* pt1 = "Hello";

Simply mean you cannot change data that pt1 is pointing to.

Both

const char* ptr1 = "Hello";
char* pt2 = "Goodbye";

create static memory for string literal. I suggest you read this.

So advantage is that you would always get compile time error on first where on second it might depend on compiler. Some compilers do it automatically. see the page I have linked to.

1

Why use the const char* form for a string

Use const char *ptr1 when the referenced string should not get modified and allow the compiler to optimize based on that.

This is always the case when assigning with string literals.

Use char *ptr2 when the referenced string might get modified.

The danger of char* pt2 = "Goodbye"; is that later code may attempt to change the data referenced by pt2, which is presently points to string literal.

chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256
0

As KamilCuk pointed out, modifying const char* pt1 = "Hello"; gives you an error already at compile time, when you can just fix the code, recompile, and everything is fine. Modifying char* pt1 = "Hello"; throws the error at runtime, and you do not want all your 1 million users to redownload and reinstall your program (You would have to first buy a better internet connection for that). So, you definitely should use const char*.

TheEagle
  • 5,808
  • 3
  • 11
  • 39
  • 2
    Your explanation is somewhat confusing: defining `pt1` one way or another does not cause an error, but defining it as `const char* pt1 = "Hello";` will allow the compiler to detect an incorrect access if somewhere else in the code you try and modify the what `pt1` points to as in `*pt1 = 'A';` – chqrlie Feb 07 '21 at 21:48
  • @Rob i did __not__ request clarification from the OP, __nor__ did i critique him; this __does__ provided an answer this question ! – TheEagle Feb 08 '21 at 03:37
0

Why use the const char* form for a string

To notify yourself and other developers that the memory the pointer points to cannot be modified. In this context const is a keyword mostly for the programmer to notify the programmer that the data the pointer points to is const.

basically anything you can do to boil the error up to be caught by the compiler is preferable, right?

Yes. That is the reason why developers push to invent better tools for static code analysis. There are many tools for static code analysis, and recently GNU compiler gcc 11 comes with internal code static analysis. It's also the reason why languages like Rust are invented and so popular. All the tools try to push as many errors as possible to be detectable "statically" - at compile time.

Gcc has also a warning with -Wwrite-strings that warns about code like char *str = "str" that assigns const literal to a non-const pointer.

KamilCuk
  • 120,984
  • 8
  • 59
  • 111
  • "To notify yourself and other developers", I would say yourself, other developers and compiler. +1 for overall answer though!!! –  Feb 07 '21 at 22:52