C programming: char * const and const char *
Difference between char * const and const char *?
const char *: char* const is a constant pointer to a character array. It means that the pointer itself is a constant, and cannot be reassigned to point to another address, but the contents of the array it points to can be modified.
char * const: char* const is a C type that represents a constant pointer to a non-constant character. This means that the memory address pointed to by the pointer cannot be changed, but the value stored at that memory address can be changed.
Example const char *:
#include<stdio.h>
void print_string(const char *str) {
while (*str != '\0') {
printf("%c", *str);
str++;
}
printf("\n");
}
int main() {
const char *text = "Hello, World!";
print_string(text);
return 0;
}
In the above example print_string() takes a const char * parameter “str”, which means that the function promises not to modify the contents of the string pointed to by "str". The while loop in print_string() uses pointer arithmetic to traverse the string, printing each character one at a time.
In main() function, a const char * variable message is declared and initialized with the string literal "Hello, World!". print_string() is then called with message as the argument. Message is a constant string, so the function cannot modify it.
Example char * const:
#include <stdio.h>
int main() {
// create a constant pointer to a string
char * const text = "Hello, World!";
// this line would result in a compilation error,
// since myString is a constant pointer
// text = "Goodbye, World!";
printf("%s\n", text);
return 0;
}
Output:
Hello, World!
In the above example, "text" is a constant pointer to a string literal "Hello, World!". Since the pointer is declared as const, it cannot be reassigned to point to a different location. We will get an error if we uncomment the line that tries to reassign "text".
We have not declared the string as a const, so we can still modify the contents of the string that "text" points to.