#include void print_number(int*...">

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

+5
source share
5 answers

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.

+14

, std::assert debug; release (.. NDEBUG), , ; , , if, .

, std::assert .

+6

:

  • .
  • . if() .
  • , .
  • , if().
+6

, , , , - :

test: main.cpp:9: int main(): Assertion `0==1' failed.

, , . wiki.

+5

Assert , - , , . , . . if() assert, Release :

void print_number(int* somePtr) {
  assert(somePtr != NULL);
  if (somePtr != NULL)
       printf ("%d\n",*somePtr);
  // else do something 
}

"//else -", , .

+2

All Articles