What Is the Datatype of String Literal in C++

What is the type of string literals in C and C++?

In C the type of a string literal is a char[] - it's not const according to the type, but it is undefined behavior to modify the contents. Also, 2 different string literals that have the same content (or enough of the same content) might or might not share the same array elements.

From the C99 standard 6.4.5/5 "String Literals - Semantics":

In translation phase 7, a byte or code of value zero is appended to each multibyte character sequence that results from a string literal or literals. The multibyte character sequence is then used to initialize an array of static storage duration and length just sufficient to contain the sequence. For character string literals, the array elements have type char, and are initialized with the individual bytes of the multibyte character sequence; for wide string literals, the array elements have type wchar_t, and are initialized with the sequence of wide characters...

It is unspecified whether these arrays are distinct provided their elements have the appropriate values. If the program attempts to modify such an array, the behavior is undefined.

In C++, "An ordinary string literal has type 'array of n const char'" (from 2.13.4/1 "String literals"). But there's a special case in the C++ standard that makes pointer to string literals convert easily to non-const-qualified pointers (4.2/2 "Array-to-pointer conversion"):

A string literal (2.13.4) that is not a wide string literal can be converted to an rvalue of type “pointer to char”; a wide string literal can be converted to an rvalue of type “pointer to wchar_t”.

As a side note - because arrays in C/C++ convert so readily to pointers, a string literal can often be used in a pointer context, much as any array in C/C++.


Additional editorializing: what follows is really mostly speculation on my part about the rationale for the choices the C and C++ standards made regarding string literal types. So take it with a grain of salt (but please comment if you have corrections or additional details):

I think that the C standard chose to make string literal non-const types because there was (and is) so much code that expects to be able to use non-const-qualified char pointers that point to literals. When the const qualifier got added (which if I'm not mistaken was done around ANSI standardization time, but long after K&R C had been around to accumulate a ton of existing code) if they made pointers to string literals only able to be be assigned to char const* types without a cast nearly every program in existence would have required changing. Not a good way to get a standard accepted...

I believe the change to C++ that string literals are const qualified was done mainly to support allowing a literal string to more appropriately match an overload that takes a "char const*" argument. I think that there was also a desire to close a perceived hole in the type system, but the hole was largely opened back up by the special case in array-to-pointer conversions.

Annex D of the standard indicates that the "implicit conversion from const to non-const qualification for string literals (4.2) is deprecated", but I think so much code would still break that it'll be a long time before compiler implementers or the standards committee are willing to actually pull the plug (unless some other clever technique can be devised - but then the hole would be back, wouldn't it?).

What is the data type of a string literal in C++?

Expressions have type. String literals have type if they are used as an expression. Yours isn't.

Consider the following code:

#include <stdio.h>

#define STR "HelloHelloHello"

char global[] = STR;

int main(void)
{
char local[] = STR;
puts(STR);
}

There are three string literals in this program formed using the same tokens, but they are not treated the same.

The first, the initializer for global, is part of static initialization of an object with static lifetime. By section 3.6.2, static initialization doesn't have to take place at runtime; the compiler can arrange for the result to be pre-formatted in the binary image so that the process starts execution with the data already in place, and it has done so here. It would also be legal to initialize this object in the same fashion as local[], as long as it was performed before the beginning of dynamic initialization of globals.

The second, the initializer for local, is a string literal, but it isn't really an expression. It is handled under the special rules of 8.5.2, which states that the characters within the string literal are independently used to initialize the array elements; the string literal is not used as a unit. This object has dynamic initialization, resulting in loading the value at runtime.

The third, an argument to the puts() call, actually does use the string literal as an expression, and it will have type const char[N], which decays to const char* for the call. If you really want to study object code used to handle the runtime type of a string literal, you should be using the literal in an expression, like this function call does.

What is the type of a string literal in C++?

The type of the string literal "Hello" is "array of 6 const char".

Ordinary string literals and UTF-8 string literals are also referred to as narrow string literals. A narrow string literal has type “array of n const char”, where n is the size of the string [...]

It can, however, be converted to a const char* by array-to-pointer conversion. Array-to-pointer conversion results in a pointer to the first element of the array.

What is the datatype of string literal in C++?

It is a const char[N] (which is the same thing as char const[N]), where N is the length of the string plus one for the terminating NUL (or just the length of the string if you define "length of a string" as already including the NUL).

This is why you can do sizeof("hello") - 1 to get the number of characters in the string (including any embedded NULs); if it was a pointer, it wouldn't work because it would always be the size of pointer on your system (minus one).

Does C have a string type?

C does not and never has had a native string type. By convention, the language uses arrays of char terminated with a null char, i.e., with '\0'. Functions and macros in the language's standard libraries provide support for the null-terminated character arrays, e.g., strlen iterates over an array of char until it encounters a '\0' character and strcpy copies from the source string until it encounters a '\0'.

The use of null-terminated strings in C reflects the fact that C was intended to be only a little more high-level than assembly language. Zero-terminated strings were already directly supported at that time in assembly language for the PDP-10 and PDP-11.

It is worth noting that this property of C strings leads to quite a few nasty buffer overrun bugs, including serious security flaws. For example, if you forget to null-terminate a character string passed as the source argument to strcpy, the function will keep copying sequential bytes from whatever happens to be in memory past the end of the source string until it happens to encounter a 0, potentially overwriting whatever valuable information follows the destination string's location in memory.

In your code example, the string literal "Hello, world!" will be compiled into a 14-byte long array of char. The first 13 bytes will hold the letters, comma, space, and exclamation mark and the final byte will hold the null-terminator character '\0', automatically added for you by the compiler. If you were to access the array's last element, you would find it equal to 0. E.g.:

const char foo[] = "Hello, world!";
assert(foo[12] == '!');
assert(foo[13] == '\0');

However, in your example, message is only 10 bytes long. strcpy is going to write all 14 bytes, including the null-terminator, into memory starting at the address of message. The first 10 bytes will be written into the memory allocated on the stack for message and the remaining four bytes will simply be written on to the end of the stack. The consequence of writing those four extra bytes onto the stack is hard to predict in this case (in this simple example, it might not hurt a thing), but in real-world code it usually leads to corrupted data or memory access violation errors.

Why the C++ compiler recognize the string type as char[]

Because a string literal in C++ is not a std::string. It is an array of const char of the appropriate size.

If you want a string literal to become a std::string, you can use the user-defined string literal operator operator""s from the standard library since C++14:

using namespace std::literals;

//...

Contains(*googleMapPtr, "operator_mykey1"s);

or alternatively write out that you want a std::string:

Contains(*googleMapPtr, std::string("operator_mykey1"));

Declare a String type in C

In C, there is no standard data type called String. It is either a string literal or a char array.

FWIW,

char text[16] = { 'E','i','n',' ','l','a','n','g','e','r',' ','T','e','x','t','\0' };

can be shortened as

char text[ ] = { "Ein langer Text"};   //modifiable, but size limited to
// the initalizer

or

char text[128] = { "Ein langer Text"};  // modifiable, with larger size than initializer

or

char *text = "Ein langer Text";  //not modifiable


Related Topics



Leave a reply



Submit