How to use variables defined by a \newcommand

Both uses are sufficient in the context you show, since they produce the same result:

enter image description here

However, in a slightly different context - removing the punctuation ! immediately following the macro use, the results are noticeably different:

enter image description here

\documentclass{article}
\newcommand{\Variable}{World}
\begin{document}
Hello \Variable{} Welcome!!

Hello \Variable Welcome!!
\end{document}

With {} the inter-word space is preserved, while it is gobbled when using \Variable without {}. This is due to the way TeX reads the input stream to identify where a macro ends.

Which is "more correct"? It depends on the context as you can use it - the ending braces {} - in some places, but it's not always necessary.

Relevant contents to read:

  • Space after LaTeX commands

  • Drawbacks of xspace


Technically you can place your \newcommand wherever you want. It is better practice to separate document structure from content. Therefore, it is customary to include all command definitions and document formatting content as part of the preamble - between \documentclass and \begin{document}.

This remains, however, purely a suggestion and depends on the end user. Some people may feel more inclined to keep definitions together with their usage (if the document provides that "flow"), others roll the more conventional way.


A macro -- more specifically, a control word that consists of one or more letters -- usually gobbles any space to its right (The exception are the macros with a single non-letter character). This allows the macro to take the next characters as first argument, so \fbox abc does the same as \fbox{a}bc. Unfortunately, macros without argument also do this, so when you start with LaTeX, sooner or later you realize that \LaTeX abc is the same as \LaTeX{}abc.

Thus, you must use "\Variable{}" or "\Variable\" (note the space after the second backslash) to avoid that. If there is no space after the macro but, say, a comma, you can simply write "\Variable,". Another option is to use the xspace package and include \xspace at the end of the macro definition, such that \Variable works well in most cases.

The \newcommand can be used in the body of the document, in the preamble o even before (above \documentclass), but the right place is the preamble as usually you do not want mix format and contents. Moreover, if the macro definition in the middle of text, it is easier to make the mistake of use the macro before of its definition.

Tags:

Macros