[Tex/LaTex] How to get character code defined with \let (! Improper alphabetic constant)

expansionmacrostex-core

Here's a example with the "! Improper alphabetic constant" error:

%% this is ok  
\newcount\mychar
\mychar=\number`a\relax
\showthe a       % shows You can't use `the letter a' after \the
\showthe\mychar  % shows 97

%% this is not ok
\let\Char=a     
\showthe\Char    % shows You can't use `the letter a' after \the
\mychar=\number`\Char\relax  % here error comes
\showthe\mychar

Setting the counter should expand till non-expandable token (in this case it's \relax). Question: why is \Char not expanded?

Best Answer

\Char is not expanded because it is not an expandable token. Unlike \def\Char{a} which expands to a \let defines a token that essentially is a and like a it does not expand.

The only way to get hold of this in classic TeX is to take \meaning\Char which will be

the letter a

split that up on spaces, and if the first two words are the letter take the letter which will be a and then use the `a syntax as you used.

Look at the source of the bm package which does a lot of this:-)


Working example (plain TeX)

\newcount\mychar

\def\zz#1{%
% catcode 11 (letter)
\ifcat a#1%
\expandafter\zza\meaning#1 \relax
\else
%other cases here
-1
\fi}

\def\zza#1 #2 #3 #4\relax{`#3 }

\let\Char=a     



\mychar=\zz{a}
\immediate\write20{a=\the\mychar}

\mychar=\zz{\Char}
\immediate\write20{\Char=\the\mychar}




\bye

which produces a log

a=97
\Char =97

showing the macro accepts explicit or implicit character tokens.

Related Question