Course contentsShow
← C
Lesson 485 of 1,2197. PointersFree lesson

Using `const char *` for safety

Using const char * for safety

What you'll learn: How to use the const keyword to prevent accidental changes to your text data and avoid program crashes.

The problem with string literals

When you write a line like char *message = "Hello";, you are pointing a variable at a piece of text stored in a "read-only" section of your computer's memory. Imagine this memory as a library book: you are allowed to read it, but if you try to scribble in the margins or erase words, the librarian (the Operating System) will immediately stop you.

In C, if you try to modify a string literal—for example, by writing message[0] = 'J';—your program will likely crash with a "Segmentation Fault." The compiler won't always warn you about this danger because char * looks like any other pointer that is allowed to change data.

The const shield

To stay safe, we use the const keyword. By declaring a pointer as const char *, you are telling the compiler: "This text should never change."

Think of const as a "read-only" lock. If you accidentally write code that tries to modify the string, the compiler will catch the mistake while you are building the program, rather than letting the program crash while someone is using it.

Seeing it in action

Here is how you protect your strings:

#include <stdio.h>

int main() {
    // This pointer is "read-only"
    const char *greeting = "Hello, World!";

    // This is safe and encouraged:
    printf("%s\n", greeting);

    // This would cause a COMPILER ERROR (which is good!):
    // greeting[0] = 'h'; 

    return 0;
}

By adding const, you turn a potential runtime disaster into a simple fix during coding. It makes your intentions clear to other programmers: "I am pointing to a constant value, and I promise not to touch it."

When to use it

You should use const char * every time you point to a string literal (text inside double quotes) or when you write a function that needs to read a string without changing it. It is one of the easiest ways to write more professional, bug-free C code.

Key takeaway

Use const char * for string literals to catch accidental modification errors during compilation instead of at runtime.