[Home]  [Edit this page]  [Recent Changes]  [Special Pages]  [Help
CppAssert

(C++) Assert

Standard macro [3].

Use assert to To use it #include the header file cassert.

There is also the possibility of using a compile time assert statements.

Page overview

  • Shorten the time finding bugs
  • Improve productivity
  • Short trick
  • Make your own assertstatement
  • 'Assert' links
  • Code links
  • References

Shorten the time finding bugs

It's hard enough to find an error in your code when you're looking for it; it's even harder when you've assumed your code is error-free
Steve McConnell


assert is a kind of if-statement, which can be cut out by the preprocessor when your program is safe.

Use assert to document internal assumptions and invariants [1,2,4]. Use assertions to verify preconditions and postconditions [4]. Use assertions for conditions that should never occur [5].

#include <cassert>
int main()
{
  const int population = 1600;
  const double fractionMales = getFraction();
  assert(fractionMales>=0.0 && fractionMales<=1.0);
  const int malePopulation = fractionMales * static_cast<double>(population);
}


In above program, the function getFraction() is called to get a fraction. In this case, the fraction can only have values from 0.0 to and including 1.0. Therefore, you assume that getFraction produces a value in this range. If this is false, you will get an error message, immediatly showing you where you were false in your assumptions.

But what is the difference with writing the code below?
  if (fractionMales<=0.0 && fractionMales>=1.0) { std::cout << "Error!"; exit(1); }


The crucial difference is that when your program is debugged in total, you do not need to comment out all these if-statements.

#define NDEBUG
#include <cassert>
int main()
{
  assert(2==3); //Of course, this is not true
}


The code above contains a false assumption. But when NDEBUG is #defined, the preprocessor removes the assert statement for you.

Improved productivity

If you have written a new function, you do not need to check it in a seperate program anymore:

std::string getFileNameExtension(const std::string& fileName)
{
  //Some way of doing this
}
int main()
{
  const std::string fileName = getSomeFileName();
  const std::string extension = getFileNameExtension(fileName);
  assert(getFileNameExtension("Test.txt")=="txt");
}


Short trick

If you have an exception, you can show it on screen WITH line number using assert:
assert(!"This is due to: ");
As !"Something" is always false (because "Something" is always true).

Using an assertion framework

There are several advanced assertion frameworks for C++ that allow you to do a lot more. ModAssert is probably the most advanced one, it has 128 different assertions, and about 60 types of analyses that you can use in them. 128 seems a lot, but it is easy to learn.

Make your own assert statement

Below is an example how to make your own assert statement.

#ifdef NDEBUG
#define assert(x) ((void)0)
#else
#define assert(x) \
  if (! (x)) \
  { \
    std::cout << "ERROR!! Assertion " << #x << " failed\n"; \
    std::cout << " on line " << __LINE__ << "\n"; \
    std::cout << " in file " << __FILE__ << "\n"; \
  }
#endif


If you work in a larger project in which assert is already #defined, you can  ?#undef the existing assert. Use the complete code below.

#ifdef assert
#undef assert
#endif
#ifdef NDEBUG
#define assert(x) ((void)0)
#else
#define assert(x) \
  if (! (x)) \
  { \
    std::cout << "ERROR!! Assertion " << #x << " failed\n"; \
    std::cout << " on line " << __LINE__ << "\n"; \
    std::cout << " in file " << __FILE__ << "\n"; \
  }
#endif


'Assert' links

Code links

References

  • 1) Herb Sutter,Andrei Alexandrescu. C++ coding standards: 101 rules, guidelines, and best practices. ISBN: 0-32-111358-6. Chapter 68: 'Assert liberally to document internal assumptions and invariants'.
  • 2) Bjarne Stroustrup. The C++ Programming Language (3rd edition).ISBN: 0-201-88954-4. Advice 24.5.18: 'Explicitly express preconditions, postconditions, and other assertions as assertions'.
  • 3) The C++ International Standard. 2003 (2nd edition). ISO/IEC 14882. Tbale 95.
  • 4)  ?Steve McConnell. Code Complete (2nd edition). 2004. ISBN: -735619670. Chapter 8.2 'Assertions', paragraph 'Guidelines for using asserts': 'Use assertions to document and verify preconditions and postconditions'.
  • 5)  ?Steve McConnell. Code Complete (2nd edition). 2004. ISBN: -735619670. Chapter 8.2 'Assertions', paragraph 'Guidelines for using asserts': 'Use assertions for conditions that should never occur'.
  • 6) Jesse Liberty. Sams teach yourself C++ in 24 hours. ISBN: 0-672-32224-2. Hour 24, chapter 'assert()': 'Use assert freely'.


last edited (August 29, 2007) by bilderbikkel, Number of views: 17952, Current Rev: 40 (Diff)

[Edit this page]  [Page history]  [What links here]  [Discuss this topic]  [Printer Friendly]  

Members

Username:

Password:


Register
Forgot Password?




Programmers Heaven - for .NET, Java, C/C++ and WEB Developers!
© 1996-2008 Community Networks Ltd. All rights reserved. Reproduction in whole or in part, in any form or medium without express written permission is prohibited. Violators of this policy may be subject to legal action. Please read Terms Of Use and Privacy Statement for more information. Development by Tore Nestenius at .NET Consultant - Synchron Data.