[Tex/LaTex] Plus equal are separated

math-mode

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

Best Answer

+ 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

Related Question