In C, how can you statically prepend the length of a fixed string to the start of that same string (BCPL-style)?

Viewed 30

For static field names, I'd like some C compiler magic to statically prepend the length of the field name, so that rather than storing "LABEL" at compile time, it would instead store "\x05LABEL". (People as ancient as me may recall that this was how BCPL stored its strings.)

The best I can come up with to achieve this is a stupendously ugly (and long-winded) macro:

#define BCPL_STRING(STRING) \
   (sizeof(STRING) == 1) ? "\x00" STRING : \
   (sizeof(STRING) == 2) ? "\x01" STRING : \
   (sizeof(STRING) == 3) ? "\x02" STRING : \
   (sizeof(STRING) == 4) ? "\x03" STRING : \
   (sizeof(STRING) == 5) ? "\x04" STRING : \
[etc]

Is there a better way to achieve this in C at compile time?

1 Answers

IMO you cant. You will get the string literal (the most likely compiler will optimize the code to the single string literal)

Any other form will require creating a normal variable and copying the data which can be only done at runtime.

BTW this macro will only work with string literals. You cant pass the char array to it (it will not work). So its usage is limited to string literals.

Related