I am trying to learn Ada, but recources are tough. I have been reading on this subject, but all explanations have been hard for me to understand. I have often seen code like this
type Stream_Element is mod 2 ** Standard'Storage_Unit;
What does this do? I have found an explanation here:
Ada also allows you to define modular types. These types are unsigned and have “wrap-around” semantics. Incrementing beyond the end of an ordinary type causes an exception, but incrementing beyond the end of a modular type wraps around to zero. In addition the operators not, and, or, and xor can be used on modular types to do bitwise manipulation. Figure 11 demonstrates.
This explanation makes sense, but I dont understand the code. what signifigance does the mod 2 ** X
have? what is the mod
for? what does the **
do?
**
is the exponentiation operator. That is, A**B
means AB.
mod
, in this context, is just the syntax you use to tell it you're defining a modular type. In this case, it means that this is an integer type whose values range from 0 to 2Standard'Storage_Unit
- 1. Standard'Storage_Unit
isn't defined by the language, but is defined by the Ada compiler you're using (the language allows compilers to define their own attributes); I believe it equals System.Storage_Unit
. This is a constant that defines the number of bits in an addressable storage unit. This constant is 8 for the vast majority of processors (since each address addresses one 8-bit byte), but there are exceptions.
So what this does is define an integer type whose values range from 0 to 255 (on most processors), i.e. the integers that will fit in a byte. Since it's "modular", that also means that arithmetic operations on the type wrap around (i.e. if you add 130 + 130, you will get 4, and Constraint_Error
will not be raised). Modular types also have bitwise operators and
, or
, and xor
defined for them.