2

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?

James Parsons
  • 6,097
  • 12
  • 68
  • 108

1 Answers1

16

** 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.

ajb
  • 31,309
  • 3
  • 58
  • 84
  • 2
    Just to add, the "2 ** X" notation for modular type declarations is convention, not required. In essence, the 'X' is the number of bits that will be occupied by the modular type. One could spell it out as `type Mod_Type is mod 256;` – Marc C Apr 29 '14 at 14:20
  • 2
    @MarcC Correct, `2**X` is just an expression, and any expression is allowed, as long as it's an expression that can be computed at compile time. The expression doesn't have to be a power of 2, either; I could envision someone defining a type as `mod 60` to represent the minute hand of a clock. (The bitwise `and`/`or`/`xor` operations are still defined, although they're probably not very useful.) – ajb Apr 29 '14 at 14:39