2

I have a problem with testing whether an argument is empty or not. The following sample code should return "correct" but does not.

Example:

\documentclass{article}

\newcommand{\ifxnotworking}[1]{
\if #1{}
    correct 
\else
    false
\fi}

\begin{document}
\ifxnotworking{}
\end{document}

Comparing {}{} or with \empty has the same result. This only occurs with empty strings, as far as I know. Does anyone know why and what would be a proper Solution?

Dosy
  • 73

2 Answers2

3

The most robust way of checking for an empty argument is \if\relax\detokenize{#1}\relax as far as I know (most likely egreg shows up and gives a way more detailed answer).

So a robust command to check for emptiness would be:

\documentclass[]{article}

\makeatletter
\newcommand{\myifempty}[1]{%
  \if\relax\detokenize{#1}\relax%
    \expandafter\@firstoftwo%
  \else%
    \expandafter\@secondoftwo%
  \fi}
\makeatother

\begin{document}
\noindent
\myifempty{foo}{empty}{not empty}\\% yields "not empty"
\myifempty{}{empty}{not empty}% yields "empty"
\end{document}
Skillmon
  • 60,462
  • 3
    See https://tex.stackexchange.com/a/20064/4427 – egreg Sep 26 '17 at 15:45
  • 2
    the old-timers folklore says \if\relax\detokenize{#1}\relax was put forward by @HeikoOberdiek, but maybe he was not first (e-TeX was slowly digested by first-timers TeX macro-ers) –  Sep 26 '17 at 15:47
  • 1
    @egreg so I was right, there is a way more detailed answer you provided :) – Skillmon Sep 26 '17 at 15:49
3

There are better ways to do that, but let me explain what's going wrong.

When you call \ifxnotworking{}, TeX will replace #1 with nothing (the braces are stripped off an undelimited argument), so the input stream will have

•\if {}•correct•\else false•\fi

(where represents a space token). Now \if compares the following unexpandable two tokens (after having performed full expansion until finding two of them, but here there's no expandable token): the two unexpandable tokens are { and } which have different character code, so the test returns false.

Note that \if compares character codes.

egreg
  • 1,121,712