Skip to main content

Constant String in C

Constant String

A constant string in C is a string literal that is defined as a constant value. A constant string cannot be modified once it is defined.

The syntax for declaring a constant string is as follows:

const char *string_name = "string_value";

Explanation

  • string_name is the name of the constant string
  • "string_value" is the string literal that represents the value of the constant string.
  • The const keyword is used to indicate that the string is a constant and cannot be modified.
  • The type char * is used to declare a pointer to a string of characters.

Constant String - Example

The following code declares a constant string named greeting:

#include <stdio.h>

int main()
{
const char *greeting = "Hello, World!";
printf("%s\n", greeting);

return 0;
}
Output:

Explanation

  • The greeting string is declared as a constant and cannot be modified.
  • The printf function is then used to print the contents of the greeting string to the console.
content

It's important to note that declaring a string as a constant only makes the pointer to the string a constant, not the contents of the string itself. Therefore, you should use the const keyword with caution when working with strings in C.

String Constant

A string constant in C is a sequence of characters surrounded by double quotes.

For example:

"Hello, World!"
  • A string constant is treated as a string literal and has a type of char [].

  • It is automatically null-terminated, which means that the end of the string is indicated by the special null character ('\0').

  • The null terminator is not part of the string's length, but it is necessary for C to determine the end of the string.

  • You can use string constants to initialize string variables or pass strings as arguments to functions.

String Constant - Example

#include <stdio.h>

int main()
{
char greeting[20] = "Hello, World!";
printf("%s\n", greeting);

return 0;
}
Output:

Explanation

  • The string constant "Hello, World!" is used to initialize the string variable greeting.
  • The printf function is then used to print the contents of the greeting string to the console.

String Constant vs Constant String

Here's a table that summarizes the differences between a string constant and a constant string in C:

String ConstantConstant String
A string literal surrounded by double quotes ("string_value").A string literal that is declared as a constant value using the const keyword (const char *string_name = "string_value";).
Automatically null-terminated ('\0').Can be referenced by a constant pointer.
Not modifiable.The pointer to the string is constant, but the contents of the string are not.