tags:

views:

484

answers:

6

hi i ve been studying on openCV tutorials and came across with the "assert" function what does it do thanks

+7  A: 

Take a look at

assert() example program in C++

Many compilers offer an assert() macro. The assert() macro returns TRUE if its parameter evaluates TRUE and takes some kind of action if it evaluates FALSE. Many compilers will abort the program on an assert() that fails; others will throw an exception

One powerful feature of the assert() macro is that the preprocessor collapses it into no code at all if DEBUG is not defined. It is a great help during development, and when the final product ships there is no performance penalty nor increase in the size of the executable version of the program.

Eg

#include <stdio.h>
#include <assert.h>

void analyze (char *, int);

int main(void)
{
   char *string = "ABC";
   int length = 3;

   analyze(string, length);
   printf("The string %s is not null or empty, "
          "and has length %d \n", string, length);
}

void analyze(char *string, int length)
{
   assert(string != NULL);     /* cannot be NULL */
   assert(*string != '\0');    /* cannot be empty */
   assert(length > 0);         /* must be positive */
}

/****************  Output should be similar to  ******************
The string ABC is not null or empty, and has length 3
rahul
Shouldn't be "if NDEBUG is defined"?
RichN
Shouldn't _it_ be.... (I thought comments can be edited....)
RichN
comments can be edited by deleting the original comment.
Chris Huang-Leaver
What's that "many compilers" about? MSVC and GCC are both standards compliant on this one. Which non-compliant compilers: don't have assert; don't print a message and abort when an assert fails; use DEBUG instead of the proper NDEBUG?
Steve Jessop
+5  A: 

assert will terminate the program (usually with a message quoting the assert statement) if its argument turns out to be false. it's commonly used during debugging to make the program fail more obviously if an unexpected condition occurs.

for example:

assert(length >= 0);  // die if length is negative.

You can also add a more informative message to be displayed if it fails like so:

assert(length >= 0 && "Whoops, length can't possibly be negative! (didn't we just check 10 lines ago?) Tell jsmith");

Or else like this:

assert(("Length can't possibly be negative! Tell jsmith", length >= 0));

When you're doing a release (non-debug) build, you can also remove the overhead of evaluating assert statements by defining the NDEBUG macro, usually with a compiler switch. The corollary of this is that your program should never rely on the assert macro running.

// BAD
assert(x++);

// GOOD
assert(x);    
x++;

// Watch out! Depends on the function:
assert(foo());

// Here's a safer way:
int ret = foo();
assert(ret);
Peter
"`assert` usually raises an exception" -- in C++ it does not rise "exception" it calls abort... it is little bit different.
Artyom
UncleBens
I don't think this answer is about the same languages as the question is tagged (C and C++). In C and C++, assert does not raise an exception, it has parentheses around its argument, and the `#` character does not introduce a comment.
Steve Jessop
great points, all. I'd remove this answer now, except I can't since it's accepted...
Peter
Here are your options: Make the answer community-wiki and edit your question removing the old stuff, asking others to place the correct information. That way, downvotes won't affect your rep, and people can improve the answer.
Johannes Schaub - litb
please edit at will.
Peter
+1  A: 

Assert allows you to halt execution if a condition (assertion) is false.

For instance (Pseudocode):

Bank myBank = Bank.GetMyStuff();

assert(myBank != NULL);

// .. Continue.

If myBank is NULL, the function will stop execution, and an error produced. This is very good for making certain reusable code accept correct conditions, etc.

Kyle Rozendo
You want to assert(myBank != NULL) if you want to halt when myBank is NULL.
indiv
Gah thanks, fingers quicker than the mind moment.
Kyle Rozendo
A: 

It is a function that will halt program execution if the value it has evaluated is false. Usually it is surrounded by a macro so that it is not compiled into the resultant binary when compiled with release settings.

It is designed to be used for testing the assumptions you have made. For example:

void strcpy(char* dest, char* src){
    //pointers shouldn't be null
    assert(dest!=null);
    assert(src!=null);

    //copy string
    while(*dest++ = *src++);
}

The ideal you want is that you can make an error in your program, like calling a function with invalid arguments, and you hit an assert before it segfaults (or fails to work as expected)

Yacoby
Asad Khan
Because you shouldn't ever pass a null pointer to strcpy. It is one of those things that Should Not Happen. If a null pointer has been passed it indicates that something at a higher level has messed up. At best you end up having to crash the program further from the problem due to unexpected data values (either dest being incorrect or null).
Yacoby
A: 

stuff like 'raises exception' and 'halts execution' might be true for most compilers, but not for all. (btw are there assert statements that really thrwo exceptions?)

Here's an interesting, slightly different meaning of assert used by c6x and other TI compilers: upon seeing certain assert statements, these compilers use the information in that statement to perform certain optimizations. Wicked.

Example in C:

int dot_product(short *x, short *y, short z)
{
  int sum = 0
  int i;

  assert( ( (int)(x) & 0x3 ) == 0 );
  assert( ( (int)(y) & 0x3 ) == 0 );

  for( i = 0 ; i < z ; ++i )
    sum += x[ i ] * y[ i ];
  return sum;
}

This tells de compiler the arrays are aligned on 32bits boundaries, so the compiler can generate specific instructions made for that kind of alignment.

stijn
So what do they do if the assert is false and NDEBUG is not set? If this is the version of assert from <assert.h>, then the standard requires that it print a message and abort. Obviously the standard doesn't say they aren't allowed to optimise based on the truth of the statement, but to be compliant they still have to abort if it's false.
Steve Jessop
they follow standard behaviour
stijn
+2  A: 

The assert computer statement is analogous to the statement make sure in English.

Blake7