The program prompts the user to enter the information of the passengers that are flying from one place to another on a specific date. In order to ensure that the value of the number of passengers is not zero or negative, an assertion is used. The assert expression validates the value assigned to the noOfPassengers variable. It checks whether the value of the noOfPassengers variable is greater than 0 or not. If it is, the program will continue to execute the rest of the statements; otherwise, the filename and the line number are sent to the standard error and the program is aborted.
If the assert statement is validated, that is, if the value assigned to noOfPassengers is more than 0, then the user is asked to enter the other details of the passengers such as where the flight is going from, where the flight is going to, and the date of the journey. The entered information is then displayed on the screen.
The program is compiled using GCC, as shown in the following screenshot. Because no error appears during compilation, this means the assertdemoprog.c program is successfully compiled into a .exe file: assertdemoprog.exe. On executing the file, the user is prompted to enter the number of passengers flying. If the number of passengers entered is a positive value, the program will run perfectly, as shown in the following screenshot:
While executing the program for the second time, if the value entered is negative or zero for the noOfPassengers variable, an error will be displayed showing the program name and line number, and the program is aborted. The specified error message, "Number of passengers should be a positive integer", will be displayed:
Voilà! We have successfully applied assertions to validate our data.