#define FOO(x) "1234" #x "5678"
const char *mystr1 = FOO(\n);
const char *mystr2 = FOO(\x20);
...as far as I can tell, it is.
6.10.3.2 implies that it "does the right thing" as long as the input is
a pre-processing token and the output is a valid character string literal.
\n is two valid pre-processing tokens due to the text at 6.4#3 and
6.4.6, and that is stringized and then treated the same way as "\n" etc.
Some background:
The explanation of why I want to do this, is that I want to create
constant strings with a length at the beginning and the nicest approach
that I'm leaning towards is:
#define XSTR(x, y) #x y
const char *mystr = XSTR(\4, "1234");
...which seems nicer than the only real alternative of:
#define XSTR(x, y) x y
const char *mystr = XSTR("\4", "1234");
...but if anyone knows of a nicer way of doing the above, that would be
even better :).
--
James Antill -- ja...@and.org
C String APIs use too much memory? ustr: length, ref count, size and
read-only/fixed. Ave. 55% overhead over strdup(), for 0-20B strings
http://www.and.org/ustr/
Actually so long as the argument to the macro is a sequence of pp tokens.
What actually makes this work is the phases of translation (5.1.1.2)
which puts macro processing before string literal processing.
[Cross posted with followups set to clc.]
James Antill <james-netn...@and.org> wrote:
> The short form of my question is, is this snippet valid C:
>
> #define FOO(x) "1234" #x "5678"
>
> const char *mystr1 = FOO(\n);
> const char *mystr2 = FOO(\x20);
>
> ...as far as I can tell, it is.
[It is.]
> 6.10.3.2 implies that it "does the right thing" as
> long as the input is a pre-processing token and the
> output is a valid character string literal.
> \n is two valid pre-processing tokens due to the
> text at 6.4#3 and 6.4.6, and that is stringized and
> then treated the same way as "\n" etc.
>
> Some background:
>
> The explanation of why I want to do this, is that
> I want to create constant strings with a length at
> the beginning and the nicest approach that I'm
> leaning towards is:
>
> #define XSTR(x, y) #x y
> const char *mystr = XSTR(\4, "1234");
>
> ...which seems nicer than the only real alternative of:
>
> #define XSTR(x, y) x y
> const char *mystr = XSTR("\4", "1234");
>
> ...but if anyone knows of a nicer way of doing the above,
> that would be even better :).
Ditch the macro and just write...
const char *mystr = "\4" "1234";
...or...
const char *mystr = "\0041234";
Note that octal can be confusing at a glance...
const char *mystr = "\010" "12345678"; /* 10 or 8? */
--
Peter