43

I have the following inline code:

$\texttt{TEST}(v *= 2, v += 2, v = 4)$

But when it is rendered, the plus is very far away from the equal sign. How can I overcome this problem and make LaTeX consider += as a single operator?

rendered

1
  • Also, maybe you want to use some sort of code environment and font (fixed size) to insert code into your PDF's, instead of a math environment, such as listings (or verbatim if all else fails)
    – Thomas
    Commented Jul 1, 2013 at 22:46

2 Answers 2

57

+ is a binary operator and = is a binary relation. When TeX finds the sequence

v + = 2

it transforms it into

Ord Bin Rel Ord

but a Bin is not allowed before a Rel, so it's changed into an Ord.

Solutions:

\documentclass{article}

\newcommand{\pluseq}{\mathrel{+}=}
\newcommand{\asteq}{\mathrel{*}=}

\begin{document}

$\texttt{TEST}(v \asteq 2, v \pluseq 2, v = 4)$

\end{document}

or, manually,

\documentclass{article}

\begin{document}

$\texttt{TEST}(v \mathrel{*}= 2, v \mathrel{+}= 2, v = 4)$

\end{document}

These exploit the fact that TeX doesn't insert any space between two consecutive Rel symbols.

enter image description here

You can also define a macro that switches the behavior, so you can type the formulas more naturally:

\documentclass{article}

\newcommand{\switch}{%
  \mathcode`+=\numexpr\mathcode`+ + "1000\relax % turn + into a relation
  \mathcode`*=\numexpr\mathcode`* + "1000\relax
}

\begin{document}

$\switch\texttt{TEST}(v *= 2, v += 2, v = 4)$

$a+=b \quad \begingroup\switch a+=b\endgroup \quad a+=b$
\end{document}

I added a nonsense line to show that \switch respects grouping. The scope of \switch ends with the formula (or group) in which it's issued.

enter image description here

6
  • Very good explanation. Commented Jul 1, 2013 at 13:04
  • Can there be a libe break between two rel symbols?
    – Aditya
    Commented Jul 1, 2013 at 17:48
  • 1
    @Aditya No, only after a relation symbol; consecutive ones are treated as a unit. Try $\relpenalty-10000 a==b$\bye and see; of course one could add a penalty in between to explicitly allow a line break.
    – egreg
    Commented Jul 1, 2013 at 17:54
  • Good. Curiously, the newcommand doesn't work for me. I had to type \mathrel{+}= inside my equations.
    – erickrf
    Commented Apr 30, 2014 at 3:41
  • @erickrf Do you refer to \newcommand{\pluseq}{\mathrel{+}=}? Can you show an example of this failure? Maybe with a new question.
    – egreg
    Commented Apr 30, 2014 at 9:06
16

enter image description here

$\texttt{TEST}(v \mathrel{{*}{=}} 2, v \mathrel{{+}{=}} 2, v = 4)$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .