4
votes

I am self-teaching myself the Ada Programming language and in the text book I am using there is an exercise to print out the factorial value of a number entered by the user. My program compiles and does run fine and I do get the expected output, but if I type in the value of 13, the program crashes and raises an error.

I have no idea why the number 13 does this. Is it an error with the IDE (I use GNAT Studio) and I currently use the Ada 2012 standard. Here is my code:

with Ada.Text_IO;
use Ada.Text_IO;
with Ada.Integer_Text_IO;
use Ada.Integer_Text_IO;

-- procedure main - begins the program
procedure main is
   counter : Integer := 1;
   number : Integer := 0;
   factorial : Integer := 1;
begin
   New_Line;
   
   while counter <= 5 loop
      Put("Enter an integer: ");
      Get(number);
      
      for Count in 1 .. number loop
         factorial := factorial * Count;
      end loop;
      
      Put_Line("Factorial value is: " & integer'image(factorial));
      factorial := 1;
      
      counter := counter + 1;
   end loop;
   
   New_Line;
end main; -- end procedure main

Error Message is this: raised CONSTRAINT_ERROR : main.adb:35 overflow check failed [2021-04-11 13:25:10] process exited with status 1, elapsed time: 02.07s

It seems like such a small issue, but I would just be interested to know if there is something wrong with the code that is creating this, or is it just a general bug with the software I use.

Thank you in advance.

1
I’d like to know what you think main.adb:35 overflow check failed could have meant? Also, the constraint error would have happened at line 19 in the code you show, which only has 29 lines anyway, so your actual code must have been different. (Just in case it’s not clear - main.adb:35 means "line 35 of file main.adb").Simon Wright
Overflow generally means when memory overruns the assigned buffer value. C had issues with Scanf and Gets. What threw me was the CONSTRAINT error. Having never used Ada before, I come from a mainly Java background, it was puzzling. Thank you for your input.Ada Lovelace

1 Answers

5
votes

Factorial of 12 is 479,001,600. Multiply by 13 to get factorial of 13, and the value is 6,227,020,800 which is larger than can fit in a 32-bit binary number.

So the Constraint_Error is telling you that the type Integer cannot represent factorial of 13 -- the computation overflowed. If you want to compute larger factorials, you must use a "wider" integer type. Note that the width of Integer is compiler-specific, although guaranteed to be at least 16 bits. Some other compiler might use 64-bit Integers. Normal advice for Ada is to define your own integer types (type XX is range 0 .. 83838 or whatever) depending on what you need.

Otherwise your program looks ok, from the Ada point of view.