Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

User-Defined String Literals Vs. Other User-Defined Literals

Let's consider the following quote from the C++11 standard (the N3376 draft, to be precise):

(2.14.8.5)

If L is a user-defined-string-literal, let str be the literal without its ud-suffix and let len be the number of code units in str (i.e., its length excluding the terminating null character). The literal L is treated as a call of the form

     operator "" X (str , len )

Whereas for all the other types of user-defined literals (floating-point, integer, character) the length is never passed along even if the literal itself is passed as a string. For example:

42_zzz; // calls operator "" _zzz("42") and not operator "" _zzz("42", 2)

Why is there this distinction between string and non-string user-defined literals? Or should I say, why does the implementation pass len for UD string literals? The length, just as in case of other literals, could be deduced by null-termination. What am I missing?

like image 955
Armen Tsirunyan Avatar asked Oct 28 '12 19:10

Armen Tsirunyan


People also ask

What are the two types of string literals?

A string literal with the prefix L is a wide string literal. A string literal without the prefix L is an ordinary or narrow string literal. The type of narrow string literal is array of char .

What are user defined literals?

A literal is used for representing a fixed value in a program. A literal could be anything in a code like a, b, c2. , 'ACB', etc. Similarly, User-Defined Literals (UDL) provides literals for a variety of built-in types that are limited to integer, character, floating-point, string, boolean, and pointer.


2 Answers

For a string literal it is reasonably conceivable that a null character is embedded in the sequence of the string, e.g., "a\0b". To allow the implementation to consume the entire string literal, even if there is an embedded null character, it needs to know the length of the literal. The other forms for user-defined literals cannot contain embedded zero characters.

like image 52
Dietmar Kühl Avatar answered Sep 20 '22 00:09

Dietmar Kühl


Strings are always null terminated in C/C++ but it never mean that they can't contain embedded \0 character, you may have "1234\05678" and while this string is null terminated, it contain an extra '\0` in it.

like image 34
BigBoss Avatar answered Sep 21 '22 00:09

BigBoss