What is the difference between \def and \newcommand?

\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.


Adding to Andrew's already good response, the one thing that \def can do that \newcommand cannot is define commands that take delimiters other than braces. For example, if you want to be able to write \foo<hello> and have the ‘hello’ interpreted as an argument, you can write

\def\foo<#1>{...something with #1...}

You can also have commands that read input up to the next brace, such as

\def\foobar#1#{\framebox[#1]}
\foobar 47pt {hello}

For a combination of the extensibility of \def with the ease-of-use of \newcommand, check out David Kastrup's suffix package. Very handy when you want to define custom markup for your document.

Also look at the LaTeX3 package xparse which takes a more structured and generalised look at how \newcommand should work.


Here is a summary of the main points made by the other answers. In each case, click on the ▶ symbols for more details.

  • \newcommand is part of LaTeX; \def is part of TeX. [▶]

  • \newcommand fails if the command is already defined; \def doesn't. [▶]

  • \newcommand provides a convenient syntax for specifying the number of arguments, and specifying a (single) optional argument; \def enables pattern-matching on the form of its arguments, which makes it more general but also less readable. [▶]

  • \newcommand can't define a command whose name starts with "end"; \def can. [▶]

  • \newcommand defines "long" commands; \def (unless \long\def is used) defines short ones. (The arguments of a "long" command can include paragraph breaks.) [▶]

Tags:

Macros