Hexadecimal Escape Sequence
Walter Murray
walter at hpclwjm.HP.COM
Wed Jan 17 05:04:52 AEST 1990
Steve Hosgood writes:
> I recently discovered in K&R Edition 2 (ANSII C) that the hex escape
> sequence will accept any number of valid hex characters after the "\x".
> This means that the printf statement:-
> printf("\x1bfred"); /* i.e "<ESC>fred" */
> ..suddenly failed in a program when we updated from Microsoft 4.0 to
> 5.1 recently.
> According to K&R2, (my only reference), MSC5.1 interprets this correctly
> as "<hex BF>red", and 4.0 was wrong to limit itself to 2 hex chars following
> the \x. It seems that an infinite number of hex characters may follow the
> \x sequence, though what happens if the result fails to fit in a char is
> undefined.
A Standard-conforming compiler is required to produce a diagnostic if
the value of a hexadecimal escape sequence doesn't fit in an unsigned
char.
> Is this what you'd call "expected behaviour"?
It's for the benefit of implementations where a char is more than
eight bits.
> After all, the octal escape sequence limits itself to 3 characters...
True. Hexadecimal escape sequences are different.
> If it IS correct, how do you write "<ESC>fred" using a hex escape? I
> ended up having to use the octal escape in the end, which seems rather
> an inelegant method.
You use adjacent string literals. You can safely write
printf("\x1b" "fred");
or
#define ESC "\x1b"
printf(ESC "fred");
This works because escape sequences are converted to single characters
prior to the concatenation of adjacent string literals.
Walter
----------
More information about the Comp.std.c
mailing list