25

Could someone please show me how to get LaTeX to properly typeset the -=, += assignment operators. I have tried

$a -= 1$
$a\texttt{-=}1$
$a\verb!-=!1$

but they all look really ugly. I have been searching all over to find a solution for this, but apparently I am the only one with this problem. And I only have two such assignments in my whole document, so I am not interested in typesetting arbitrary blocks of C++ code, just those two assignments

6
  • 3
    Welcome to TeX.SX! You can have a look at our starter guide to familiarize yourself further with our format. Commented Nov 16, 2013 at 12:22
  • What do you mean with "nicely"? Don't you like the font or the justification? Commented Nov 16, 2013 at 12:23
  • 4
    I suspect you want to use a package like listings or minted to format computer program source code, particularly in C or C++. Commented Nov 16, 2013 at 14:32
  • 1
    I second Benjamin McKay. TeX' math mode is for typesetting maths. Maths is a declarative language, not an imperative one, therefore assignment operators don't make much sense; if you try to write imperative code as maths equations it's going to become extremely messy because there's no real support for structuring loop constructs etc.. And without such constructs, there's no point in using assignment/modification at all, so if you only have two such assignments in your document, you're simply doing maths wrong, nothing else. Commented Nov 16, 2013 at 16:58
  • I'm interested in what type of document you are writing.
    – marczellm
    Commented Nov 16, 2013 at 18:13

2 Answers 2

32

these two-part operators have to be declared as operators to get the correct spacing on either side. the following definitions will take care of that, while forcing each individual part to be treated as an ordinary character.

\newcommand{\pluseq}{\mathrel{{+}{=}}}
\newcommand{\minuseq}{\mathrel{{-}{=}}}

the result may still not be to your liking, but if you find the two parts to be farther apart than you think they should be, that can be adjusted by some negative space between them.

enter image description here

0
18

I'd propose

$a\mathrel{-}=1$

enter image description here

For a general purpose macro, define

\newcommand{\assign}[2]{%
  \mathrel{#1}\mathrel{#2}%
}

so that you can call

$a \assign{-}{=} 1$
$a \assign{=}{+} 1$
$a \assign{++}{=} 1$

enter image description here

0

You must log in to answer this question.

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