Asssertions in Programming

Assertions are special statements provided by different programming languages to check the programming logic. It is strategically placed in the program to verify some expressions that should always hold to be true.  Assertions take a boolean expression that should evaluate to true at that program point where the assert statement is placed.


For example, checking denominator to be non-zero to save from divide by zero exceptions that may lead to failure later.

An example of an assertion in C++:

    #include <stdio.h>
    #include <assert.h>
    
    int fact (int a)
    {
    if ((a == 0) || (a == 1))
        return 1;
    else
        return a * fact(a-1);
    }
    int main() {
      int a, b;
    
      printf("Input number to calculate factorial:\n");
      scanf("%d", &a);
     
      assert(a <= 12);
      b = fact(a);
    
      printf("%d\n", b);
    
      return 0;
    }
Since factorials of numbers over 12 can result in an integer overflow exception, it is better to assert if the number is greater than 12.