[Tex/LaTex] Setting \pagestyle{fancy} seems into create an error

conditionalsfancyhdrheader-footer

Calling fancy page style is somehow apparently causing the following condition to test true.

\documentclass{article}
\usepackage{fancyhdr}
\pagestyle{fancy}
\ifcsname chapter\endcsname%
    \renewcommand{\chapter}{}
\fi
\pagestyle{empty}
\begin{document}
testing
\end{document}

If I place \pagestyle{fancy} after the conditional, \ifcsname chapter....\fi, everything works. This is an article class, so this conditional should be false. If I call \pagestyle{plain}, it doesn't matter where I place it.

Why does this order matter?

Best Answer

The page style fancy (\ps@fancy) contains:

\@ifundefined{chapter}{...}{...}

That is the LaTeX test for undefined:

\def\@ifundefined#1{%
  \expandafter\ifx\csname#1\endcsname\relax
    \expandafter\@firstoftwo
  \else
    \expandafter\@secondoftwo
  \fi}

\csname has the side effect that it defines an undefined command with the meaning \relax:

\show\chapter
\pagestyle{fancy}% \@ifundefined{chapter}{...}{...}
\show\chapter

The meaning of \chapter changes:

> \chapter=undefined.
l.3 \show\chapter

? 
> \chapter=\relax.
l.5 \show\chapter

Now \chapter is defined for e-TeX's \ifcsname and \renewcommand{\chapter}{} is called that again used the LaTeX idea of undefined: A command is undefined if it is undefined or has the meaning of \relax. As result \renewcommand complains that `\chapter is not defined.

e-TeX's \ifcsname does not have the side effect and lets the command untouchted. (Also it is internally optimized in the sense that it does not create a hash table entry.)

The test needs to be a little longer:

\ifcsname chapter\endcsname
  \ifx\chapter\relax
  \else
    \renewcommand\chapter{}
  \fi
\fi

A defined \chapter might confuse packages and macros about the capabilities of the class (article does not have chapters). If the purpose of the mysterious \renewcommand\chapter{} is to undefine chapter, then it will fail, because \chapter remains defined with the meaning of an empty macro. A command can be undefined by assigning it to an undefined macro:

\ifcsname chapter\endcsname
  \let\chapter\UnDeFiNeD
\fi