Any advantage of using assert instead of using a simple "if"?
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 typing using assert?
Yours faithfully
assert - Document your assumptions in code. if to handle various logical scripts.
Now in your particular case, think from the point of view of the developer of the print_number () function.
For example, when you write
void print_number(int* somePtr) {
assert (somePtr!=NULL);
printf ("%d\n",*somePtr);
}
you want to say that
In my print_number function, I assume that the pointer is always null. I would be very surprised if this value is null. I don’t want to consider this scenario in my code at all.
void print_number(int* somePtr) {
if (somePtr != NULL)
printf ("%d\n",*somePtr);
// else do something
}
, , , print_number . , , else.
, , , . if. , - , . assert.