[Tex/LaTex] reading through the definition of `\cfrac` in AMSMath

amsmathfractions

I am reading through the definition of \cfrac in AMSMath

\newcommand{\cfrac}[3][c]{{\displaystyle\frac{%
  \strut\ifx r#1\hfill\fi#2\ifx l#1\hfill\fi}{#3}}%
  \kern-\nulldelimiterspace}

Can someone explain a bit how this code works? Immediately see the newcommand used to define \cfrac and that it take three arguments. I don't know what [c] means here.

Then onto the main portion. Continued Fractions are presented display style. However,

  • can someone explain to me how l#1 and r#1 are used? they look like conditionals
  • I checked that #2 and #3 correspond to the numerator and denominator

I can sort of distinguish the important parts

{{\displaystyle
\frac{ \strut
    \ifx r#1\hfill\fi
    #2
    \ifx l#1\hfill\fi}
{#3}} 
\kern-\nulldelimiterspace}

Then if I replace #2 with A and #3 with B I get a nice fraction… just like \frac{A}{B}

\ifx is always followed by the backwards-if \fi — then what are the conditionals r#1 and l#?

and what is the rule of \strut ?


There is discussion of \kern and \nulldelimiterspace in other parts of this site

How to compute exact width added by \left. \right

Best Answer

\newcommand{\cfrac}[3][c]{...

defines a command with two mandatory arguments and one optional so the use is \cfrac{a}{b} or \cfrac[r]{a}{b} with the former being equivalent to \cfrac[c]{a}{b}.

\ifx is a tex primitive which tests the following two tokens so if #1 (the value of the optional argument) is r then

\ifx r#1

is true so \hfill is added, otherwise control jumps to \fi.

so

\cfrac[r]{a}{b} is \frac{\strut\hfill a}{b}

\cfrac[c]{a}{b} is \frac{\strut a}{b}

\cfrac[l]{a}{b} is \frac{\strut a \hfill}{b}

each in \displaystyle and followed by a negative space of \kern-\nulldelimiterspace

For completeness, the other commands

A \strut is an invisible zero-width rule (with height 0.7\baselineskip and depth 0.3\baselineskip) designed to fill out a normal line spacing. This ensures the numerator is given the same vertical space whether the numerator is a or A the same technique is used to give consistent spacing in matrices.

\displaystyle gives the more open style normally used in display equations such as \begin{equation} rather than inline math from $

\nulldelimiterspace is the space that you get from the "missing delimiter" in constructs such as \left\{xxxx\right. but also in particular it is added either side of fraction constructs, this allows cfrac to always have close spacing on the right hand side, as needed for continuous fractions.

The following example has exaggerated setting of \nulldelimiterspace to show the effect.

enter image description here

\documentclass{article}
\usepackage{amsmath}
\begin{document}

\nulldelimiterspace=10pt
$|\cfrac{a}{bbb}|$


$|\cfrac[l]{a}{bbb}|$


$|\cfrac[r]{a}{bbb}|$

\end{document}