From a4d7df8d1ef5994b6c9ba837955253bca54c5ca9 Mon Sep 17 00:00:00 2001 From: Antti H S Laaksonen Date: Sun, 23 Apr 2017 10:29:01 +0300 Subject: [PATCH] Show how macros may cause bugs [closes #17] --- chapter01.tex | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/chapter01.tex b/chapter01.tex index 07475b8..7d9609a 100644 --- a/chapter01.tex +++ b/chapter01.tex @@ -508,6 +508,36 @@ REP(i,1,n) { } \end{lstlisting} +Sometimes macros cause bugs that may be difficult +to detect. For example, consider the following macro +that calculates the square of a number: +\begin{lstlisting} +#define SQ(a) a*a +\end{lstlisting} +This macro \emph{does not} always work as expected. +For example, the code +\begin{lstlisting} +cout << SQ(3+3) << "\n"; +\end{lstlisting} +corresponds to the code +\begin{lstlisting} +cout << 3+3*3+3 << "\n"; // 15 +\end{lstlisting} + +A better version of the macro is as follows: +\begin{lstlisting} +#define SQ(a) (a)*(a) +\end{lstlisting} +Now the code +\begin{lstlisting} +cout << SQ(3+3) << "\n"; +\end{lstlisting} +corresponds to the code +\begin{lstlisting} +cout << (3+3)*(3+3) << "\n"; // 36 +\end{lstlisting} + + \section{Mathematics} Mathematics plays an important role in competitive