1
\documentclass{article}
\title{}
\author{}
\date{}
\begin{document}

\newcommand{\mybold}[2]{\ifnum #1=1 \textbf{#2} \else{#2} \fi}
\mybold{1}{This should be bold}

\mybold{0}{This should NOT be bold}
\end{document}

In this code, the command mybold accepts a number and text. If the number is 1 the text is emphasized and if not it doesn't. It works as expected.

\documentclass{article}
\title{}
\author{}
\date{}
\begin{document}

\newcommand{\mybold}[2]{\ifnum #1=1 \textbf\fi{#2}} \mybold{1}{This should be bold}

\mybold{0}{This should NOT be bold} \end{document}

I tried shortening the first code by putting #2 behind the if condition. However, I get too many }'s error. How do I get the second code to work?

nch7822
  • 11

2 Answers2

2

Do this.

\documentclass{article}
\title{}
\author{}
\date{}
\begin{document}

\newcommand{\mybold}[2]{\ifnum #1=1 \expandafter\textbf\fi{#2}} \mybold{1}{This should be bold}

\mybold{0}{This should NOT be bold} \end{document}

Explanation: TeX \if... commands works a bit unintuitive way, so the \textbf will "see" the \fi. Refer to What do \@firstoftwo and \@secondoftwo do?.

If you want to learn the details of TeX macro programming, resources are at Where do I start LaTeX programming?. But normally writing "simpler" code is better.

user202729
  • 7,143
  • 1
    More simple macro is: \def\mybold#1{\ifnum #1=1 \expandafter\textbf\fi} – wipet Jan 20 '23 at 21:08
  • @wipet Simpler here mean "can be understood without knowing the detail of TeX macro expansion" , but then I do link to resources if anyone want to read. – user202729 Jan 21 '23 at 00:27
0

Although user202729's answer is more to the point of the programming problem, to solve the typographic problem you may want to simply use a font switch instead of the \textbf command:

\documentclass{article}
\title{}
\author{}
\date{}
\begin{document}

\newcommand{\mybold}[2]{{\ifnum #1=1 \bfseries\fi #2}}% NOTICE the difference in grouping! \mybold{1}{This should be bold}

\mybold{0}{This should NOT be bold} \end{document}

Notice however that the two approaches are not exactly the same; there can be a difference if italic correction is needed on the switch.

Rmano
  • 40,848
  • 3
  • 64
  • 125