SunQuest
 
       C++
  Home arrow C++ arrow Page 3 - C++ Preprocessor: Always Assert Your Code ...
Dev Articles Forums 
ADO.NET  
Apache  
ASP  
ASP.NET  
C#  
C++  
ColdFusion  
COM/COM+  
Delphi-Kylix  
Design Usability  
Development Cycles  
DHTML  
Embedded Tools  
Flash  
Graphic Design  
HTML  
IIS  
Interviews  
Java  
JavaScript  
MySQL  
Oracle  
Photoshop  
PHP  
Reviews  
Ruby-on-Rails  
SQL  
SQL Server  
Style Sheets  
VB.Net  
Visual Basic  
Web Authoring  
Web Services  
Web Standards  
XML  
Dedicated Servers  
Actuate Whitepapers 
VeriSign Whitepapers 
IBM® developerWorks 
Sun Developer Network 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
C++

C++ Preprocessor: Always Assert Your Code Is Right
By: J. Nakamura
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 4 stars4 stars4 stars4 stars4 stars / 43
    2005-11-07

    Table of Contents:
  • C++ Preprocessor: Always Assert Your Code Is Right
  • Implementing Assert
  • Implementing a Simplified Assert
  • Refining Assert

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
    Iron Speed
     
    ADVERTISEMENT

    Ajax Application Generator Generate database and reporting .NET Web apps in minutes. Quickly create visually stunning, feature-rich apps that are easy to customize and ready to deploy. Download Now!

    C++ Preprocessor: Always Assert Your Code Is Right - Implementing a Simplified Assert


    (Page 3 of 4 )

    Although I am ranting about why you should use assert, this article is aimed at showing you how to implement your own version using preprocessor macros.

    Here is a very basic version that doesn’t even halt execution:

    #ifndef NDEBUG
    # define ASSERT( isOK ) \
     ( (isOK) ? \
          (void)0 : \
          (void)printf(“ERROR!! Assert ‘%s’ failed on line %d ” \
           “in file ‘%s’\n”, #isOK, __LINE__, __FILE__) )
    #else
    # define ASSERT( unused ) do {} while( false )
    #endif

    Notice that we don’t need a helper function to get information onto the screen. (I am sticking to printf in the following examples, but there is nothing stopping you from using fprintf and stderr instead.) The stringize macro operator (#) names the condition for us in the printf statement, adding quotes as well and the predefined __LINE__ and __FILE__ macros help to identify the location of the assert.

    The do { } while ( false ) statement for the unused version of assert, I used to make sure that the user cannot forget to conclude his assert statement with a semicolon. The compiler will optimize it away, and I consider it a slightly better way to say that I am not doing anything.

    We are only one step away from halting our application’s execution (don’t forget to include stdlib.h):

    #ifndef NDEBUG
    # define ASSERT( isOK ) \
     if ( !isOK ) { \
      (void)printf(“ERROR!! Assert ‘%s’ failed on line %d “ \
       “in file ‘%s’\n”, #isOK, __LINE__, __FILE__) ); \
      abort(); \
     }
    #else
    # define ASSERT( unused ) do {} while ( false )
    #endif

    In case writeString is called with a NULL pointer now, we are told what went wrong, where it went wrong and the application is halted.

    When you are using the Microsoft Visual C++ 7.1 compiler, you’ll be presented with a dialog screen:

     

    After pressing Retry you are presented with more dialogs and finally... you end up in the debugger.

    The problem with abort() is that it doesn’t let you resume execution after you’ve concluded that the assert was benign; or maybe you are interested in what happens immediately after the assert? You need to disable the assert (never a good thing), recompile and restart your application.

    There are other ways to halt execution and you will have to look in your compiler’s documentation to discover what the correct call is, but with Visual C++ it’s an interrupt call:

    __asm { int 3 }

    When our application halts again on the writeString function, we’ll encounter the following dialog (did you recognize it? We actually came across this dialog when halting the application with the abort() function!) :

    It is not a problem to continue execution now, if we think this is responsible… that is you are often recommended to implement your own assert functionality.

    Wouldn’t it be nice to be able to add some hints or remarks along with the location of the assert? When the assert fires and you don’t have a debugger available, this message might still tell you what the problem is:

    void writeString(char const *string) {
     assert(0!=string, “A null pointer was passed to writeString()!”);
     ...
    }

    More C++ Articles
    More By J. Nakamura


       · ‘this code won’t be used the next millennium, two digits are fine’Yo, C++...
       · I have been working on C,C++ for some time, and have been relying on conditionals...
       · This code doesn't compile in Visual Studio 7.1.error C2440: 'type cast' : cannot...
       · At work we are now using the assertions of ModAssert. Over the past two months we...
       · Assert may suffice for ivory tower programming; but it's no substitute for a well...
     

    C++ ARTICLES

    - Brief Introduction to the STL Containers
    - The Standard Template Library
    - Templates in C++
    - C++ Programmer Alerts
    - C++ Programming Tips
    - First Steps in (C) Programming, conclusion
    - First Steps in (C) Programming, continued
    - First Steps in (C) Programming, introduction
    - C++ Preprocessor: Always Assert Your Code Is...
    - C++ Preprocessor: The Code in the Middle
    - Programming in C
    - Temporary Variables: Runtime rvalue Detection
    - Temporary Variables: Chasing Temporaries Away
    - Temporary Variables: Temporaries Are Not Nec...
    - Temporary Variables: Keep Your Values Close,...


    Iron Speed





    © 2003-2008 by Developer Shed. All rights reserved. DS Cluster 3 hosted by Hostway