# How to test if a label exists

I have tried to follow another question but I cannot get it to work. My question is: How do print a text based on if a reference exists or not?

I have tried the following:

\usepackage{etoolbox}
\usepackage{xparse}

...

\NewDocumentCommand\calledName{m}{%
\ifcsundef{r@KN:#1}{\ref{FN:#1}}{\ref{KN:#1}}%
}

• Yes I did, sorry for not telling. – 7heViking Jul 14 '16 at 17:15
• And xparse of course... – user31729 Jul 14 '16 at 17:21
• If the label is FN:#1 or KN:#1, why are you looking for r@#! instead of r@FN:#1 or r@KN:#1? – John Kormylo Jul 14 '16 at 17:27
• Yes :) \usepackage{xparse} – 7heViking Jul 14 '16 at 17:27
• What do you expect here actually? Your check for r@foo will check whether the label named foo exists, but calling either \ref{FN:#1} or \ref{KN:#1} is useless if FN:foo or KN:foo are not defined labels – user31729 Jul 14 '16 at 17:28

Here's a way with \@ifundefined and using latex.ltx core features.

If the label KN:#1 is undefined, a reference to FN:#1 is used (or at least tried to do so.

Another way would use \getrefnumber etc. by refcount package.

\documentclass{article}

\makeatletter
\newcommand\calledName[1]{%
\@ifundefined{r@KN:#1}{%
\ref{FN:#1}%
}{%
\ref{KN:#1}%
}%
}
\makeatother

\begin{document}

\section{Foo} \label{KN:foostuffwrong}

\section{OtherFoo} \label{FN:foostuff}

\calledName{foostuff}
\calledName{stuff}

\calledName{foostuff}

\end{document}

• I like this method better as it doesn't need a new package :) – 7heViking Jul 14 '16 at 17:49