#define STR "test1"
Why does this take 6 bytes?
sizeof(STR) = 6
#define STR "test1"
Why does this take 6 bytes?
sizeof(STR) = 6
It has nothing to do with #define
. A character array would be the same size:
const char str[] = { "test1" };
sizeof (str) == 6
The reason this string is 6 bytes long is that strings in C have a terminating NUL character to mark the end.
Strings in C are arrays of char
s, with a null terminator i.e. they end with the \0
. The common alternative is Pascal-style strings, where the string stores the array of char
s without the null terminator, and stores the length of the string somewhere instead.
a #define
just does a text replacement before compiling.
#define STR "test1"
sizeof(STR);
is actually seen by the compiler as
sizeof("test1");
now why is that 6 and not 5? because there's a null terminator at the end of the string.
What the others said ... BUT
In C
, preprocessing tokens take no space. It depends on how you use them
#define STR "test1"
char x[] = STR; /* 6 bytes */
char *y = STR; /* sizeof (char*) bytes (plus possibly 6 bytes) */
int ch = STR[3]; /* 1 byte (or sizeof (int), depending on how you look at it) */
if (ch == STR[1]) /* 1 byte (or sizeof (int) or no bytes or ...) */
printf("==>" STR "<==") /* 5 bytes ??? */
The latest C compiler has a feature to guess if the person writing the program is in a learning phase and give answers which make them search wider and deeper, and thus enrich their knowledge.
After programming for some time, depending of your learning, you might see the value go down to 5. ;-)
JK.. as someone else said, it symbolically nothing at the end which ironically takes a byte.