1

Why does if-else not work correctly when it detects that a given argument is empty?

Below is my code. I want change the action argument #1 depending on whether it is empty or not. If #1 is not empty, the code works as expected. However, if #1 is empty e.g in the case of a line \foobar{}{Child3}, my code processes the code in the true part as well as in the false part of the if. The if does not work correctly. The result caused that two frames of the 2nd node were superimposed as in an attached image.

Why? And what to do to solve this problem?

\documentclass{article}
\usepackage[dvipdfmx]{graphicx} % require to color.
\usepackage{tikz}
\usetikzlibrary{trees, positioning}
\begin{document}

\begin{figure}[t]
  \newcommand{\foobar}[2]{
    \if\relax\detokenize{#1}\relax
    node(#2){Empty!!!!!}%<EMPTY>%
    \else
    node(#2){#1}%<NON EMPTY>%
    \fi
  }
  \begin{tikzpicture}[every node/.style={draw=black, thick, anchor=west}]
    \node {Root}
        child{\foobar{}{Child3}
        % child{\foobar{child3}{Child3} % no problem, insted above line.
            child{\foobar{child5}{child5}}
    }; % means end of drawing
  \end{tikzpicture}
\end{figure}

\end{document}
epR8GaYuh
  • 2,432
  • Doesn't the code lead to an error message? –  Feb 12 '20 at 06:56
  • Error alert was displayed. However, in the .log file, I cannot find "error" string. and my editor software did not show message of the error. I was bothered not to have gotten that detail. – user2058374 Feb 13 '20 at 01:28

1 Answers1

2

Your code produces an error on my machine. You cannot insert \ifs arbitrarily in the path, this can confuse the parser. However, as the \if only concerns the node contents, you can do e.g.

\documentclass{article}
%\usepackage[dvipdfmx]{graphicx} % require to color.
\usepackage{tikz}
\usetikzlibrary{trees, positioning}
\begin{document}

\begin{figure}[t]
  \newcommand{\foobar}[2]{
    node(#2){\if\relax\detokenize{#1}\relax
     Empty!!!!!
    \else
    #1
    \fi}%<EMPTY>%
  }


  \begin{tikzpicture}[every node/.style={draw=black, thick, anchor=west}]
  \node {Roo[![enter image description here][1]][1]t}
    child {\foobar{}{Child3}
      child {\foobar{child5}{child5}}
    };
   \end{tikzpicture}    
\end{figure}

\end{document}

enter image description here

However, keeping \usepackage[dvipdfmx]{graphicx} leads to strange results on my machine, so I commented it out. Here one learns that one should not use this option, so it is probably a good idea to drop it.

  • \usepackage[dvipdfmx]{graphicx} leads to strange results with pdflatex engine. But this option intend to use with dvi producing engine. On my machine, if run latex and then dvipdfmx for you code, result is fine. – Mr. Sandman Feb 12 '20 at 08:27
  • @Mr.Sandman Thanks! –  Feb 12 '20 at 15:04
  • @Schrödinger'scat and @ Mr. Sandman Thank you! my problem solved. – user2058374 Feb 13 '20 at 01:24