I would like to allow special characters (in my case, an underscore) to be displayed in a loop.
Say I have this MWE:
\documentclass[12pt]{article}
\usepackage{pgffor}
\begin{document}
\foreach \g in {ab, cd}{
\g
}
\end{document}
This works, and prints ab cd.
However, if I instead tweak cd in the loop to be c_d, I get an error.
\documentclass[12pt]{article}
\usepackage{pgffor}
\begin{document}
\foreach \g in {ab, c_d}{
\g
}
\end{document}
Error:
Missing $ inserted.
Now, normally, I would just write c_d as c\_d, but I can't do so given the loop. Is there a workaround? Perhaps a function that allows the special characters to be displayed? Note that in my application, I would like to be able to print c_d in a figure caption or in a subsection.

c\_din the loop?\foreach \g in {ab, c\_d}{ \g}works for me. – Qrrbrbirlbel Dec 06 '22 at 17:40\g. I get this error if I replacec_dwithc\_d:Missing endcsname inserted <to be read again> protect– bill999 Dec 06 '22 at 18:05\foreachmight not be the right tool for the job to begin with. It will also depend on what “opening a file” entails. – Qrrbrbirlbel Dec 06 '22 at 18:27\includegraphics.) – bill999 Dec 06 '22 at 18:33