# Embedding if statements in environments

I am trying to write an environment so that I can toggle on and off the answers to questions on a hand out. I also want the answers to appear red and then the main text go back to black after the question.

My code is as follows,

\documentclass{article}
\usepackage[utf8]{inputenc}

\usepackage{geometry}
\usepackage{siunitx}
\usepackage[dvipsnames]{xcolor}
\usepackage{gensymb}

\newif\ifstudent  % This controls if it is a student version or not

\studenttrue

%\studentfalse

{\ifstudent
\\
\vspace{#1}
\\
\else\\
\color{red}
}
{
\color{black}\\
\fi
}

\begin{document}

At 18\degree C, gold has a resistance of 180 $\si{\Omega}$. When the temperature is increased, the resistance increases to 200 $\si{\Omega}$. Calculate the new temperature if the temperature coefficient of resistivity for gold is 0.0034.

$$R_T=R_0\left[1+\alpha(T-T_0)\right]$$
\\
$$T=\frac{\frac{R_T}{R_0}-1}{\alpha}+T_0=\frac{\frac{200\;\si{\Omega}}{250\;\si{\Omega}}-1}{0.0034}+18\degree\si{C}=116\degree\si{C}$$
\end{document}


Unfortunately I get an error of <inserted text> \fi <*> main.tex if i run it like it is. It runs fine if i switch it to true.

• You should close the \if...\fi before the end of the first half of the environment. Remember that environments are implemented as two macros, \answer and \endanswer (in this case). For example, the arguments for \answer are not available for \endanswer. – John Kormylo Apr 4 at 18:50

May I suggest the following.

Notes: It is always good to start and end with a \par. The best way to hide something is to put it into a savebox (which is probably what \phantom does). For an environment, the logical choice is lrbox. Inside an environment, group, or savebox, you don't need to restore the color.

\documentclass{article}
\usepackage[dvipsnames]{xcolor}
\usepackage[utf8]{inputenc}

\usepackage{geometry}
\usepackage{siunitx}

\usepackage{gensymb}

\newif\ifstudent  % This controls if it is a student version or not
\studenttrue
%\studentfalse

\ifstudent\vspace{#1}\fi% #1 can only be used in first half of environments
\begin{lrbox}{0}\minipage{\linewidth}\color{red}}%
{\endminipage\end{lrbox}%
\ifstudent\else\usebox0\par\fi
}

\begin{document}

At 18\degree C, gold has a resistance of 180 $\si{\Omega}$. When the temperature is increased, the resistance increases to 200 $\si{\Omega}$. Calculate the new temperature if the temperature coefficient of resistivity for gold is 0.0034.

$$R_T=R_0\left[1+\alpha(T-T_0)\right]$$
$$T=\frac{\frac{R_T}{R_0}-1}{\alpha}+T_0=\frac{\frac{200\;\si{\Omega}}{250\;\si{\Omega}}-1}{0.0034}+18\degree\si{C}=116\degree\si{C}$$