Sizeof string literal
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 characterf
and the terminating NUL.foo
is a pointer (edit: regardless of qualifiers), and pointers seem to be 4 bytes long on your system..- For
bar
the case is the same as"f"
.
Hope that helps.
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
.