T.T.T.
T.T.T.

Reputation: 34523

How many bytes does a #define string (string literal) take?

#define STR "test1"

Why does this take 6 bytes?

sizeof(STR) = 6

Upvotes: 2

Views: 4408

Answers (7)

Seth
Seth

Reputation: 46423

Why does this take 6 bytes?

Actually, it will take (6 bytes × the number of times you use it), because it's a preprocessor macro.

Try const char *STR = "test1" instead.

Upvotes: 1

Rajan
Rajan

Reputation: 922

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.

Upvotes: 0

pmg
pmg

Reputation: 108978

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 ??? */

Upvotes: 1

Ben Voigt
Ben Voigt

Reputation: 283634

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.

Upvotes: 5

miked
miked

Reputation: 3598

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.

Upvotes: 5

Michael Williamson
Michael Williamson

Reputation: 11438

Strings in C are arrays of chars, 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 chars without the null terminator, and stores the length of the string somewhere instead.

Upvotes: 2

DigitalRoss
DigitalRoss

Reputation: 146043

There is a trailing '\0' at the end.

Upvotes: 17

Related Questions