The size of a string literal consisting of escaped characters

Code in question:

#include <iostream>
#include <cstring>
using namespace std;

int main()
{
    cout << sizeof("\n\r\t") << endl; // prints 4
    cout << strlen("\n\r\t") << endl; // print 3
    return 0;
}

I got confused because I always thought it was standard that sizeofchar was always 1 byte, but in the code above it prints 4.

Is there an explanation for this, or is there an exception to this rule for escaped characters? Please enlighten me

+4
source share
4 answers

it

"\n\r\t"

is a so-called string literal. It is stored in memory as a constant array of characters with a terminating zero. Each escape character is one character.

So, this string literal has three explicit characters plus terminatimg zero. There are four characters in the literal text.

strlen, . , .

strlen , , .

sizeof, , . const char[4], sizeof 4. , .

+4

, strlen , sizeof . C strlen , :

.

, , ++ 2.14.5 8 :

UTF-8 . " n const char", n - , , (3.7).

15 :

[...] - , , , , \0.

sizeof, , 5.3.3 3:

[...] . , n n .

+6

, \0.

\n, \r, \t \0 - , , 4 !

, :

The string literal is of type "an array of size N from [const] char", where N includes terminal null.

Remember that arrays do not break into pointers when passed to sizeof.

+2
source

By calling sizeof()in a string literal, you are literally trying to find the size of the string literal in memory.

This included a null terminating character, which is automatically added to the string literal by your compiler.

+1
source

Source: https://habr.com/ru/post/1527421/


All Articles