[Tex/LaTex] the difference between \def and \newcommand


Inspired by a question about \let and \def, I have some that essentially all boil down to asking

What are the differences between \def and \newcommand?

In particular, I wonder

  1. Is it possible to have parameters passed to \defed commands, both optional and required?
  2. Is there a \redef command equivalent to \renewcommand?
  3. I have only ever used \newcommand — is there any reason I should change that habit?

but I welcome comments on anything else I may not have thought of in this list!

Best Answer

\def is a TeX primitive, \newcommand is a LaTeX overlay on top of \def. The most obvious benefits of \newcommand over \def are:

  1. \newcommand checks whether or not the command already exists
  2. \newcommand allows you to define an optional argument

In general, anything that \newcommand does can be done by \def, but it usually involves a little trickery and unless you want something that \newcommand can't do, there's no point in reinventing the wheel.

In answer to your particular points:

  1. Yes and No. A command defined using \def has to know exactly what its options are, and how they will be presented to it. However, a TeX command can be a bit clever and examine things other than its arguments. The way that optional commands are handled is to look at the next character in the stream and if it is [ then one version of the command is called, whereas if it isn't then another is called. So if you're prepared to do some hackery, then optional arguments are possible via \def, but it isn't half so easy as \newcommand.
  2. No. Since \def doesn't check for a command already being defined, you can redefine stuff simply using \def again. To get the checking, you need to use the \@ifundefined command (note the ampersat (@) sign!).
  3. No!

There's probably lots more to be said on the differences, but that's enough from me.