Why don't ANSI C compilers flag the use of a string literal argument in a function call in which the correponding parameter does not have a const qualifier? For example, the following code could generate an exception by trying to write to read only memory.
void somefunc(char buffer[10]);
void somefunc(char buffer[10]) {
int i;
for (i = 0; i < 10; i++)
buffer[i] = 0;
}
int main(int argc, char **argv) {
somefunc("Literal");
return 0;
}
This situation could be identified at compile time but VS2010 and gcc don't appear to do so. Calling somefunc with a const char* argument will generate a compiler warning.
string is an object meant to hold textual data (a string), and char* is a pointer to a block of memory that is meant to hold textual data (a string). A string "knows" its length, but a char* is just a pointer (to an array of characters) -- it has no length information.
In C++, string literals are stored in arrays of const char , so that any attempt to modify the literal's contents will trigger a diagnostic at compile time. As Christian points out, the const keyword was not originally a part of C.
They are not const in C, but are in C++. They aren't generally writable as noted by others, but they don't behave as constants. There are some weird things you can't do, like 'case "abc"[2]:' in C, but you can in C++ where string literals are constant.
In C programming language, *p represents the value stored in a pointer and p represents the address of the value, is referred as a pointer. const char* and char const* says that the pointer can point to a constant char and value of char pointed by this pointer cannot be changed.
It is a K&R legacy. Fixing it would break a million programs.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With