assert.h

A couple of days back, I attended Br. Jayaraj ji’s class(by the way, he is one of the best guys in Amrita University, quoting a senior’s words). He was teaching some basic concepts in C and C++, concepts that we should have known by now, having studied these programming languages for quite sometime. I came across a very easy method to detect errors in the program. One can use the assert function defined in the header file assert.h, to find out errors in the program. This is very useful in cases where you have to check whether a particular value in greater or lesser than a specified value. The following code would help you to understand things better.

#include<stdio.h>
#include<assert.h> 
main() {
    int i, element_number, array[10];
    printf("Enter the size of the array - ");
    scanf("%d", &element_number);
    assert(element_number > 0);
    assert(element_number <= 10);
    printf("Enter the elements to be inserted in the array - ");
    for (i = 0; i <= element_number; i++) 
        scanf("%d", &array[i];
    for (i = 0; i <= element_number; i++)
        printf("%d ", array[i]);
}

Here the assert function checks if the number of elements to be entered is greater than 0 but is lesser than the size of the maximum size of the array. This helps the user check if he has entered the correct value for the number of elements to be entered.

One disadvantage of the assert() function is that it does not work functions with equality checking. It can only be used for checking if the considered value is greater than or lesser than a particular value. Consider the following piece of code :

#include<stdio.h>
#include<assert.h>
main() {
 float i  =  0.3;
    printf("Value of i - %f\n", i);
    i+=0.3;
    printf("The incremented value of i is %f\n", i);
    assert(i == 0.6);
    i+=0.3;
    printf("The incremented  value of i is %f", i);
}

When run, the printf statements before assert function, get printed on the screen. However, the expression in the assert function, gets evaluated as false and hence the program gets aborted at that particular point, and this has nothing to do with the number of zeroes at the end of the number. The floating point numbers are represented in a different manner. They are represented in the form of fraction(or mantissa), exponent, and base. Hence the unexpected result.

Happy coding 🙂

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s