    <rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:admin="http://webns.net/mvcb/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:content="http://purl.org/rss/1.0/modules/content/">
     <channel>
        <title>ACCU  :: 10 Things You Always Wanted to Know About Assert (But Were
Afraid to Ask)</title>
        <link>https://members.accu.org/index.php/articles/1205</link>
        <description>Professionalism in Programming</description>
        <dc:language>en-us</dc:language> 
        <dc:creator>Administrator</dc:creator> 
        <admin:generatorAgent rdf:resource="http://www.xaraya.org" /> 
        <admin:errorReportsTo rdf:resource="mailto:webeditor@accu.org" />
       <sy:updatePeriod>hourly</sy:updatePeriod>
       <sy:updateFrequency>1</sy:updateFrequency>
       <docs>http://backend.userland.com/rss</docs>




<div class="xar-mod-head"><span class="xar-mod-title">Programming Topics + CVu Journal Vol 15, #2 - Apr 2003</span></div>

<table border="0" cellpadding="1" cellspacing="0">
    <tbody>
    <tr>
        <td valign="top">
            Browse in :
       </td>
       <td valign="top">

                                            <a href="https://members.accu.org/index.php/articles/">All</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c13/">Topics</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c65/">Programming</a>
<br />

                                            <a href="https://members.accu.org/index.php/articles/">All</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c76/">Journals</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c77/">CVu</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c109/">152</a>
<br />

                                            <a href="https://members.accu.org/index.php/articles/c65-109/">Any of these categories</a>

                    -                        <a href="https://members.accu.org/index.php/articles/c65+109/">All of these categories</a>
<br />
</td>
   </tr>
   </tbody>
</table>




<div class="xar-error">
   <p>
 <strong>Note:</strong> when you create a new publication type,
the articles module will automatically use the templates
<em>user-display-[publicationtype].xt</em>
and <em>user-summary-[publicationtype].xt</em>.
If those templates do not exist when you try to preview or display a new article,
you'll get this warning :-)  Please place your own templates in themes/<em>yourtheme</em>/modules/articles . The templates will get the extension .xt there. </p>
</div>
<div class="xar-norm xar-standard-box-padding">
   <h1><strong>Title:</strong>&nbsp;10 Things You Always Wanted to Know About Assert (But Were
Afraid to Ask)</h1>
<p><strong>Author:</strong>&nbsp;</p>
<p>
<strong>Date:</strong> 03 April 2003 13:15:56 +01:00 or Thu, 03 April 2003 13:15:56 +01:00</p>
<p><strong>Summary:</strong>&nbsp;<p>This article is aimed primarily at those who are unfamiliar with assertions. However, even advanced programmers may make one or two new discoveries.</p></p>
<p><strong>Body:</strong>&nbsp;<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e20" id="d0e20"></a></h2>
</div>
<p>This article is aimed primarily at those who are unfamiliar with
assertions. However, even advanced programmers may make one or two
new discoveries.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e24" id="d0e24"></a>1. How do I
call <tt class="function">assert</tt>?</h2>
</div>
<p>Write</p>
<pre class="programlisting">
assert(condition);
</pre>
<p>Some examples:</p>
<pre class="programlisting">
assert(i &lt; 0);
assert(ptr);
assert(!str.empty());
</pre></div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e38" id="d0e38"></a>2. What does
<tt class="function">assert</tt> do?</h2>
</div>
<p>If assertions are enabled (see point 8) and the condition is
false, the assertion fails, displaying a diagnostic message, then
calling <tt class="function">abort</tt>, a C and C++ standard
library function that terminates your program without calling
destructors or performing much else in the way of clean-up.
Otherwise, if the condition is true, program execution continues as
normal.</p>
<p>The exact format of the diagnostic message is implementation
defined, but it must include the condition, converted to a string,
plus the source file name and line number of the <tt class=
"function">assert</tt> call. C99, the latest patchily-adopted
standard version of C, additionally requires that the name of the
function containing the <tt class="function">assert</tt> be
given.</p>
<p>Ensure your asserted condition have no side-effects: the mere
evaluation of the condition should not affect program behaviour.
There are a number of reasons for this, separation of concerns
being one of them.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e59" id="d0e59"></a>3. Why would I
want to use <tt class="function">assert</tt>?</h2>
</div>
<p><tt class="function">assert</tt> allows you to document your
assumptions about your program's state in code, in such a way that
they can be verified automatically at runtime. The dramatic effects
of an assertion failure will alert you to any cases where your
assumptions do not hold. This makes <tt class=
"function">assert</tt> a powerful bug detection tool.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e72" id="d0e72"></a>4. Which
headers contain <tt class="function">assert</tt>?</h2>
</div>
<p><tt class="function">assert</tt> is available in both C and C++.
In both standard versions of C, C90 and C99, it lives in the
C-style header file <tt class="filename">&lt;assert.h&gt;</tt>. In
standard C++ it lives in the C++-style header file <tt class=
"filename">&lt;cassert&gt;</tt> also.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e88" id="d0e88"></a>5. Is
<tt class="function">assert</tt> a member of the <tt class=
"literal">std</tt> namespace?</h2>
</div>
<p>No: <tt class="function">assert</tt> is a macro so it is not a
member of a namespace even when you use the C++-style header file.
Alternatively, given the way macros are globally visible, we could
say it is a member of all namespaces.</p>
<p><tt class="function">assert</tt> is an odd choice of name for a
macro, since it is all lower case. This is one instance where you
should not follow the language standards' example in your own code:
any macros you write should be named using <tt class=
"literal">ALL_CAPS</tt>.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e109" id="d0e109"></a>6. Should I
use <tt class="function">assert</tt> to check for I/O errors?</h2>
</div>
<p>Almost always not. Most programs should be designed to cope
gracefully with I/O errors and the behaviour of a failed assertion
is anything but graceful.</p>
<p>Use <tt class="function">assert</tt> only to verify assumptions
that must always be true for the program to function correctly: in
other words to detect bugs. The same arguments apply to other
runtime checks that should be able to fail gracefully: don't use
<tt class="function">assert</tt>.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e125" id="d0e125"></a>7. Should I
use assert to check for memory allocation failures?</h2>
</div>
<p>No. Memory allocation failure is another example of a failure
that should be tolerated gracefully, which makes <tt class=
"function">assert</tt> an unsuitable choice. See the previous
point.</p>
<p>In C++ when you are using <tt class="literal">new</tt>, this is
doubly misguided because new does not return a <tt class=
"literal">NULL</tt> pointer on allocation failure, it throws a
<tt class="exceptionname">std::bad_alloc</tt> exception.</p>
<pre class="programlisting">
// Please don't do this!
foo* ptr = new foo;
assert(ptr);  // Wrong. Doubly.
</pre></div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e146" id="d0e146"></a>8. How do I
remove assertions from a program?</h2>
</div>
<p>Assertions are most useful during program development and
testing. Although some people advocate leaving assertions enabled
in released code, it is common also to disable them, particularly
when the overhead of the checking would affect your program's
ability to hit its performance targets. It is not my intention to
get into a full discussion as to the pros and cons of disabling
assertions in release builds. I believe both approaches to be valid
in some circumstances.</p>
<p>Disabling <tt class="function">assert</tt> calls is supported as
standard: <tt class="function">assert</tt> is defined in such a way
that if the macro <tt class="literal">NDEBUG</tt> is defined before
inclusion of <tt class="filename">&lt;assert.h&gt;</tt> or
<tt class="filename">&lt;cassert&gt;</tt>, <tt class=
"function">assert</tt> calls compile to a no-op. In other words,
somewhere in these header files lies code equivalent to</p>
<pre class="programlisting">
#ifdef NDEBUG
#define assert(cond)
#endif
</pre>
<p>This provides another good reason why the <tt class=
"function">assert</tt> condition should not have any side-effects:
if <tt class="literal">NDEBUG</tt> is defined, then the condition
will never be evaluated.</p>
<p>Many compilers support debug and release modes of compilation.
Often <tt class="literal">NDEBUG</tt> is defined automatically when
compiling in release mode. See your compiler's documentation for
more information.</p>
<p>Beware: <tt class="filename">&lt;assert.h&gt;</tt> and
<tt class="filename">&lt;cassert&gt;</tt> are unlike most header
files with respect to multiple inclusion, which may have a
different effect from single inclusion. Each time you include one
of these files, any previous definition of <tt class=
"function">assert</tt> is undefined (using <tt class=
"literal">#undef</tt>) and <tt class="function">assert</tt> is
redefined. If <tt class="literal">NDEBUG</tt> is defined then the
no-op definition of <tt class="function">assert</tt> is given,
otherwise the normal, checking, definition of <tt class=
"function">assert</tt> is given. This allows you to write code like
this:</p>
<pre class="programlisting">
// This code is allowed, but not recommended.
#include &lt;cassert&gt;

void with_assertions_enabled(int i) {
  assert(i &gt; 0);  // Will be checked.
  ...
}

#define NDEBUG
#include &lt;cassert&gt;

void with_assertions_disabled(int i) {
  assert(i &gt; 0);  // Not checked. No-op.
  ...
}
</pre>
<p>Code like this is confusing so the practice is not recommended.
Nonetheless, you may see it in other people's work, so it is good
to be aware of it.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e216" id="d0e216"></a>9. Does
<tt class="function">assert</tt> support design by contract?</h2>
</div>
<p>Design by contract is a term to describe a strict approach to
verifying program assumptions and is most fully documented by
Bertrand Meyer, the creator of the language, <span class=
"emphasis"><em>Eiffel</em></span>. Briefly, he divides conditions
into three categories:</p>
<div class="itemizedlist">
<ul type="disc">
<li>
<p>Pre-conditions that must be true on function entry.</p>
</li>
<li>
<p>Post-conditions that must be true on function exit.</p>
</li>
<li>
<p>Invariants that must be true both on function entry and on
function exit.</p>
</li>
</ul>
</div>
<p>The fundamental principle behind design by contract is that a
correctly written function promises that its post-conditions and
invariants will be true on exit <span class="emphasis"><em>provided
that</em></span> its pre-conditions and invariants are true on
entry.</p>
<p><tt class="function">assert</tt> provides a mechanism for
checking pre-conditions, post-conditions and invariants in C and
C++ programs. However, it is fair to say that other languages,
particularly Eiffel, more fully support design by contract. For
more details of Meyer's thinking see [<a href=
"#Meyer">Meyer</a>].</p>
<p>For checking pre-conditions it is permissible to use an if
statement and a <tt class="literal">throw</tt> instead of an
<tt class="function">assert</tt>. For example,</p>
<pre class="programlisting">
void foo(int i) {
  if(i &lt; 1)
    throw std::range_error(&quot;foo: i &lt; 1&quot;);
}
</pre>
<p>versus</p>
<pre class="programlisting">
void foo(int i){
  assert(i &gt;= 1);
}
</pre>
<p>There is no hard and fast rule as to which technique is best. I
prefer assertions for testing pre-conditions when the calling code
will be written by myself or another member of my development team.
When the calling code will be written by external developers I
prefer to use exceptions here.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e265" id="d0e265"></a>10. What
about extending <tt class="function">assert</tt>?</h2>
</div>
<p>Many compilers' assert macros go beyond what is required by the
language standards. It is common to be offered the choice to
continue execution past an assertion failure (just as if the
assertion had not failed) or to drop into a debugger.</p>
<p>Furthermore, developers often create their own <tt class=
"function">assert</tt>-like macros which provide more flexibility.
Typical extensions are:</p>
<div class="itemizedlist">
<ul type="disc">
<li>
<p>Extensions similar to those offered by vendors and discussed
previously, for working with compilers whose vendors provide only
the standard-mandated assertion support.</p>
</li>
<li>
<p>Providing more user-friendly messages. Particularly useful for
those whose release builds contain enabled assertions.</p>
</li>
<li>
<p>Multiple levels of protection, instead of the all-or-nothing
<tt class="literal">NDEBUG</tt> approach. For example, if you
define <tt class="literal">ASSERT_QUICK</tt> (for conditions that
are checked quickly) and <tt class="literal">ASSERT_SLOW</tt> (for
conditions that take longer to check), you have three speed versus
bug detection tradeoffs available: you can build with both enabled,
only enabling <tt class="literal">ASSERT_QUICK</tt> or with neither
enabled.</p>
</li>
<li>
<p>Assertions that throw on failure (the Eiffel approach).
Pre-condition testing aside (see previous point), I don't recommend
this approach: assertion failures should be loud and proud, not
open to silent <tt class="literal">catch</tt>-and-continue. If you
go down this road, think very carefully about the interactions with
exception safety.</p>
</li>
<li>
<p>Assertions that automatically log their message to an error
file, or to the Windows Event Log. They could even send an e-mail
or an SMS message to a system administrator.</p>
</li>
</ul>
</div>
<p>Extending <tt class="function">assert</tt> can be very useful
but, to avoid confusion with the standard macro, please use a
different name!</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e314" id="d0e314"></a>Summary</h2>
</div>
<p>We have discussed what assertions are, how they behave, when to
use them and, just as importantly, when <span class=
"emphasis"><em>not</em></span> to use them. Finally we explored
some more advanced issues such as extensions to the basic
<tt class="function">assert</tt> functionality.</p>
<p>You should now know enough to use assertions productively. Even
making the basic transition from no assertions to employing the
humble standard <tt class="function">assert</tt>, can, I believe,
bring a significant quality boost to the development process.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e330" id=
"d0e330"></a>Acknowledgements</h2>
</div>
<p>Thanks to Heidi for her help with reviewing this article.</p>
</div>
<div class="bibliography">
<div class="titlepage">
<h2><a name="d0e335" id="d0e335"></a>References</h2>
</div>
<div class="bibliomixed"><a name="Meyer" id="Meyer"></a>
<p class="bibliomixed">[Meyer] Bertrand Meyer discusses design by
contract: <span class="bibliomisc"><a href=
"http://archive.eiffel.com/doc/manuals/technology/contract/"
target="_top">http://archive.eiffel.com/doc/manuals/technology/contract/</a></span></p>
</div>
</div>
</p>
<p><strong>Notes:</strong>&nbsp;</p>
<p><em>More fields may be available via dynamicdata ..</em></p>
</div>
</channel>
</rss>
