The type of a u"..." string literal is const char16_t[N], where N is the size of the string in UTF-16 code units including the null terminator.
String Length in C Using the sizeof() OperatorWe can also find the length of a string using the sizeof() Operator in C. The sizeof is a unary operator which returns the size of an entity (variable or value). The value is written with the sizeof operator which returns its size (in bytes).
The reason this string is 6 bytes long is that strings in C have a terminating NUL character to mark the end. That's not an array, it's a pointer to a string literal, and sizeof(str) will return the size of the pointer type for your machine.
So this string implementation is 32 because that's the way it was built in this implementation and it will by 16 in other implementations and 64 in yet another. The size of the string will (like water) depend on the environment it is used in.
sizeof("f")
must return 2, one for the 'f' and one for the terminating '\0'.sizeof(foo)
returns 4 on a 32-bit machine and 8 on a 64-bit machine because foo is a pointer.sizeof(bar)
returns 2 because bar is an array of two characters, the 'b' and the terminating '\0'.The string literal has the type 'array of size N of const char
' where N includes the terminal null.
Remember, arrays do not decay to pointers when passed to sizeof
.
sizeof
returns the size in bytes of its operand. That should answer question number 1. ;) Also, a string literal is of type "array to n const char" when passed to sizeof
.
Your test cases, one by one:
"f"
is a string literal consisting of
two characters, the character f
and the terminating
NUL.foo
is a pointer (edit: regardless of qualifiers), and pointers seem to be 4 bytes long on your system..bar
the case is the same as "f"
.Hope that helps.
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