Given this code :
#include <stdio.h>
#include <assert.h>
void print_number(int* somePtr) {
assert (somePtr!=NULL);
printf ("%d\n",*somePtr);
}
int main ()
{
int a=1234;
int * b = NULL;
int * c = NULL;
b=&a;
print_number (c);
print_number (b);
return 0;
}
I can do this instead :
#include <stdio.h>
#include <assert.h>
void print_number(int* somePtr) {
if (somePtr != NULL)
printf ("%d\n",*somePtr);
// else do something
}
int main ()
{
int a=1234;
int * b = NULL;
int * c = NULL;
b=&a;
print_number (c);
print_number (b);
return 0;
}
So , what am I gaining by using assert ?
Regards
assertis to document your assumptions in the code.ifstatement is to handle different logical scenarios.Now in your specific case, think from the point of view of the developer of the
print_number()function.For example when you write
you mean to say that,
In my
print_numberfunction I assume that always the pointer coming is not null. I would be very very surprised if this is null. I don’t care to handle this scenario at all in my code.But, if you write
You seem to say that, in my
print_numberfunction, I expect people to pass a null pointer. And I know how to handle this situation and I do handle this with anelsecondition.So, sometimes you will know how to handle certain situations and you want to do that. Then, use
if.Sometimes, you assume that something will not happen and you don’t care to handle it. You just express your surprise and stop your program execution there with assert.