ASSERT function use ?

i have seen many GOOD coders using the function called assert() in C++ . i don’t know why do they feel need for this… ??? how i can use this ?? can anyone please explain how to use assert and how it can help me ?

The Assert() function in the .NET framework is primarily used for unit testing. It will display a message is the condition is false:

if-else statement does the same job why use this ??

If-else statement does not do exactly this.Assert terminates the program with a message quoting the assert statement if its argument/assertion turns out to be false.Assert is equivalent to make-sure in English Language.

Cosider the following Example:

(1)
		char * str="Hello";
        assert(strlen(str)<0); //Your statement is false that means assertion will work ,so  
                            //the program terminates exactly at this statement
                            //and display the following message on the terminal:
                            //"prog: prog.cpp:8: int main(): Assertion `strlen(str)<0' failed."
                            //So,at this point ,you can easily make necessary changes in your program and can resume the execution.
		

 (2)
        char * str="Hello";
		assert(str==NULL);
                           //Your statement is false that means assertion will work ,so  
                          //the program terminates exactly at this statement
                          //and display the following message on the terminal:
                          //"prog: Assertion failed: str==NULL,' failed."
                          //So,at this point you can easily make necessary changes in  your program and can resume the execution,to identity other bugs .

If-then-else statement does not halt execution if a condition (your_assertion_statement) is true/false.

Also,the best feature of Assert is,you can disable all of the assertion statement (as no one wants to print the statement used for debugging in final output )in a single go , simply including a line the macro

  #define NDEBUG

at the beginning of the code ie. before the inclusion of assert.h /cassert header file .

2 Likes

thanks i got the point clear !!