Documents I found about \newcommand only uses \newcommand{\cmd}{defn}, and doesn't talk about \newcommand\cmd{defn} form, but I see \newcommand\cmd{defn} form frequently, especially in nested definitions. What's the difference between these?
1 Answers
The official LaTeX manual (Lamport's book) always consistently braces arguments, so x^{2} not x^2 and \newcommand{\foo}{zzz}.
However at the very lowest level of TeX, its parser for macro arguments reports a single unbraced token and a token in braces in exactly the same way. So in fact the latex definition of \newcommand can not tell if you use
\newcommand\cmd{abc}
or
\newcommand{\cmd}{abc}
The difference is completely invisible to the macro layer.
It would be possible (essentually using \@ifnextchar\lbrace to look for a brace and complain if it wasn't there but only at some cost in complexity of the code and speed.
In practice for commands that (should) have a single command token as argument the form without braces is perfectly good so I would use
\newcommand\cmd{abc}
\setlength\zzz{3pt}
etc.
Some people over-use this and for example write \frac12 for \frac{1}{2} dropping the braces for arguments that typically have longer strings but are single tokens in a particular case. This works, for the same reason, \frac can not tell that the braces have been dropped`, but I would say this is very bad style and makes the source hard to read and leads to hard to spot errors.
Note that in error cases ommitting the braces can change the behaviour.
\documentclass{article}
\begin{document}
\newcommand\zz123{zzz}
\texttt{\meaning\zz}
\newcommand{\ZZ123}{ZZZ}
\texttt{\meaning\ZZ}
\end{document}
Here \newcommand\zz1 is valid and the same as \newcommand{\zz}{1} so \zz is defined to be 1 and 23{zzz} just gets left over and typeset.
However with \newcommand{\zz123} the entire group is taken as the command name (it could at this point give an error that it is not a single token, but doesn't) and actually a strange sequence of internal definitions get made and no useful definition is made at all even though no error is given.
- 757,742
\cmd) or arbitrary many tokens inside a set of braces (like{abc}). The macro using that argument will receive the tokens with the outer set of braces stripped. This way, when\newcommandgrabs its first argument both\cmdand{\cmd}will result in\newcommandacting on\cmd. – Skillmon Nov 06 '21 at 15:34\cmdforms a single token, there is no difference. The distinction is purely preference based, from a programmer's perspective. Some prefer the braces as a form of consistency. (I do not) – Steven B. Segletes Nov 06 '21 at 15:35\newcommand\zz123{zzz}and\newcommand{\zz123}{zzz}are different (although neither handle the error well) – David Carlisle Nov 06 '21 at 15:36