Search

Sponsored Links

Meta

Categories

Archives

Recent Posts

RSS Feeds

27
Dec

ASSERTions explained

Related Blog Items

Asserts are assumptions on which program or function is based on. Assertion failure often indicates a possible bug in program.
Programmers inserts asserts to minimize debugging time and with help of asserts there is fair chance of catching bugs easy and in early phase of development.

inbreif, Assert asserts what you want to do is what you do

an example how assert works:
assert(cond) used for checking whether cond is true

x=3;
ASSERT(x > 4);

in the above snippet, assert failure happens as x is 3, but assertion says that it should be greater than 4.

implementation of assert:
As a compiler definition, define ASSERT to be one of:
/DASSERT_LEVEL= ASSERT_FATAL
/DASSERT_LEVEL = ASSERT_WARNING

#define ASSERT_FATAL 1
#define ASSERT_WARN  2
 
#ifndef NDEBUG
  #if   (ASSERT_LEVEL == ASSERT_FATAL)
    #define ASSERT(cond) \
    if( !(cond) ) \
    { \
      do { \
        printf( "Assertion " #cond  " failed:%s[%d]",__FILE__,__LINE__); \
      } while (0); \
      DebugBreak(); \
    }
  #elif (ASSERT_LEVEL == ASSERT_WARNING)
    #define ASSERT(cond) \
    if( !(cond) ) \
    { \
      do { \
        printf( "Assertion " #cond  " failed:%s[%d]",__FILE__,__LINE__); \
      } while (0); \
    }         
  #else
    #define ASSERT(cond) ((void)0)
  #endif
#endif

Difference between error handling and assertions:
Error handling handles routine errors occured while assertions should be used for something which
should never happen until unless there is something wrong fundamentally.

Caution with Assertions:
While disabling assertions, the whole assertion code got deleted from base code, so make sure you do not
use any functional code which is required even if we disable assertion.

ex:

int x=5;
 
func()
{
  x++;
  return x;
}
 
ASSERT(func() == 6)
 
b = x; //disabling assertion makes b value as 5 which ideally should be 6
//using b for something

[tags]ASSERTions explained, assert, assert source code, assert implementation, assert program, assert details[/tags]

Popularity: 3%

You need to log on to convert this article into PDF


Related Blog Items

1 Comment

Leave a comment

*
To prove you're a person (not a spam script), type the security word shown in the picture.
Anti-spam image