# [Tex/LaTex] How to test if a label exists

cross-referencingmacros

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}}%
}


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}