On 1 Aug, 12:31, rahul <rahulsin...@gmail.comwrote:
/* the proper way to do it
fp = fopen (FILE_NAME, "rb");
assert (fp != NULL);
No. Absolutely NOT. This is utterly broken, wrong, and
heinous. This is NOT what assert is for. At all. Arghh.
If you want, you might do:
fp = Fopen( ... );
assert( fp != NULL );
This would serve as documentation to the maintainer that
the Fopen call will never return a NULL pointer. Or you
can do things like:
for( i = 0; i < N; i++) {
...
}
assert( i == N);
This documents to the maintainer that the loop
is constructed such that it will always terminate with i
hitting the upper bound. The purpose of assert is to
validate that something you believe must be true is
in fact true. Often as pre-conditions in a function call:
void add( const int *a, const int *b, int *c, size_t N )
{
size_t i;
assert( a != NULL );
assert( b != NULL );
assert( c != NULL );
for( i = 0; i < N; i++ )
c[i] = a[i] + b[i];
}
This is far safer than simply adding a comment that states
that none of the arguments can be a null pointer, since it
aborts when the unwary programmer attempts to pass a null
pointer. It is NOT doing validation. If you want to write
a function that validates, you can't use assert. For example:
int add( int *a, int *b, int *c)
{
int status = 0;
int A,B;
A = ( a == NULL ) ? 0 : *a;
B = ( b == NULL ) ? 0 : *b;
if( c == NULL )
status = -1
else
*c = A + B;
return status;
}
Here, there are some questions. For example, perhaps you want
this function to never overflow. So perhaps you might want to
ensure that it is never called with *a or *b larger than INT_MAX/2.
In that case, look through your code; if you believe that
condition is true, then make it an assertion.
assert is NOT for data validation, or to check a function call.
It is used to validate your logic and the implementation. It
should be thought of as documentation. You are telling both
the compiler and the maintainer that you believe something
will be true. If it is not, the compiler will tell you that
you are wrong by causing a run-time abort. Anytime you look at
a piece of code and think something like, "okay, right here,
either i is positive or j is odd", then write it out:
assert( i 0 || j % 2 );
This is much better than a comment for two reasons ( at least ):
1) It removes the ambiguity about the word "positive" (does it
include zero or not?)
2) It is validated by the compiler.