Added full C++ book.

This commit is contained in:
Robert Tice
2017-11-22 17:05:45 -05:00
parent 874b417886
commit 8fbff40812
43 changed files with 5658 additions and 0 deletions

View File

@@ -3,3 +3,4 @@ djangorestframework
django-cors-headers
pyyaml
markdown
docutils

View File

@@ -0,0 +1,48 @@
Preface
*******
Nowadays it seems like talking about programming languages is a bit passé. The technical wars of the past decade have subsided and today we see a variety of high-level and well-established languages offering functionality that can meet the needs of any programmer.
Python, Java, C++, C#, and Visual Basic are recent examples. Indeed, these languages make it easier to write code very quickly, are very flexible, offer features with highly dynamic behavior, and some even allow compilers to deduce the developer's probable intent.
Why, then, talk about yet another language? Well, by addressing the general programming market, the aforementioned languages have become poorly suited for working within the domain of high-integrity systems. In highly reliable, secure and safe applications such as those found in and around airplanes, rockets, satellites, trains, and in any device whose failure could jeopardize human life or critical assets, the programming languages used must support the high standard of software engineering necessary to maintain the integrity of the system.
The concept of verification---the practice of showing that the system behaves and performs as intended---is key in such environments. Verification can be accomplished by some combination of review, testing, static analysis, and formal proof techniques. The increasing reliance on software and increasing complexity of today's systems has made this task more difficult. Technologies and practices that might have been perfectly acceptable ten or fifteen years ago are insufficient today. Thankfully, the state of the art in analysis and proof tools and techniques has also advanced.
The latest revisions of the Ada language, Ada 2005 and Ada 2012, make enhanced software integrity possible. From its inception in the 1980s, Ada was designed to meet the requirements of high-integrity systems, and continues to be well-suited for the implementation of critical embedded or native applications. And it has been receiving increased attention recently. Every language revision has enhanced expressiveness in many areas. Ada 2012, in particular, has introduced new features for contract-based programming that are valuable to any project where verification is part of the engineering lifecycle. Along with these language enhancements, Ada compiler and tool technology has also kept pace with general computing developments over the past few years. Ada development environments are available on a wide range of platforms and are being used for the most demanding applications.
It is no secret that we at AdaCore are very enthusiastic about Ada, but we will not claim that Ada is always the solution; Ada is no more a silver bullet than any other language. In some domains other languages make sense because of the availability of particular libraries or development frameworks. For example, C++ and Java are considered good choices for desktop programs or applications where a shortened time to market is a major objective. Other areas, such as website programming or system administration, tend to rely on different formalisms such as scripting and interpreted languages. The key is to select the proper technical approach, in terms of the language and tools, to meet the requirements. Ada's strength is in areas where reliability is paramount.
Learning a new language shouldn't be complicated. Programming paradigms have not evolved much since object oriented programming gained a foothold, and the same paradigms are present one way or another in many widely used languages. This document will thus give you an overview of the Ada language using analogies to C++ and Java---these are the languages you're already likely to know. No prior knowledge of Ada is assumed. If you are working on an Ada project now and need more background, if you are interested in learning to program in Ada, or if you need to perform an assessment of possible languages to be used for a new development, this guide is for you.
This document was prepared by Quentin Ochem, with contributions and review from Richard Kenner, Albert Lee, and Ben Brosgol.
..
.. This chapter should be unindented when it is ready
How to Run the Examples
***********************
Learning any language is best done by using it and seeing it in action. Therefore, each section of this document will include plenty of examples, available from [URL]. To run these examples, you will need a recent version of the GNAT compiler. The latest GNAT GPL distributions for OS X, Windows, and Linux are freely available from [URL] and are suitable to use with this guide. GNAT Pro, which is the commercial version for those developing professional applications, may also be used.
In the directory for each example you'll find a *.gpr* file (that is, a "GNAT Project File"). This file contains information on where to find source code, where to put object and executable files, and compilation and build settings. We've made all the *.gpr* files in each example directory specify the same layout: source files are located at the top level alongside the *.gpr* file, and object and executable files are to be written to an *obj*/ sub-directory.
From the command line, compilation can be performed with a call to *gprbuild*:
.. code-block:: script
$> gprbuild -P project.gpr
You can run the freshly compiled code in the *obj*/ directory the same way as you would any other executable on your platform. Invoke the example with:
.. code-block:: script
$> ./obj/main
Source code for the examples is stored in *.ads* and *.adb* files. To view the contents of these files you can use your favorite programmer's editor or use GPS, the GNAT Programming Studio. To open GPS you can double-click on the *.gpr* project file or invoke GPS on the command line:
.. code-block:: script
$> gps -P project.gpr
To compile your project using GPS, use the top-level menu to invoke Build -> Project -> main.adb (or use the keyboard shortcut, F4). To run the main program, use Build -> Run -> main (the keyboard shortcut for this is Shift + F2).

View File

@@ -0,0 +1,39 @@
Basics
******
Ada implements the vast majority of programming concepts that you're accustomed to in C++ and Java: classes, inheritance, templates (generics), etc. Its syntax might seem peculiar, though. It's not derived from the popular C style of notation with its ample use of brackets; rather, it uses a more expository syntax coming from Pascal. In many ways, Ada is a simpler language---its syntax favors making it easier to conceptualize and read program code, rather than making it faster to write in a cleverly condensed manner. For example, full words like **begin** and **end** are used in place of curly braces. Conditions are written using **if**, **then**, **elsif**, **else**, and **end if**. Ada's assignment operator does not double as an expression, smoothly eliminating any frustration that could be caused by **=** being used where **==** should be.
All languages provide one or more ways to express comments. In Ada, two consecutive hyphens ``--`` mark the start of a comment that continues to the end of the line. This is exactly the same as using **//** for comments in C++ and Java. There is no equivalent of **/\*** ... **\*/** block comments in Ada; use multiple ``--`` lines instead.
Ada compilers are stricter with type and range checking than most C++ and Java programmers are used to. Most beginning Ada programmers encounter a variety of warnings and error messages when coding more creatively, but this helps detect problems and vulnerabilities at compile time---early on in the development cycle. In addition, dynamic checks (such as array bounds checks) provide verification that could not be done at compile time. Dynamic checks are performed at run time, similar to what is done in Java.
Ada identifiers and reserved words are case insensitive. The identifiers *VAR*, *var* and *VaR* are treated as the same; likewise **begin**, **BEGIN**, **Begin**, etc. Language-specific characters, such as accents, Greek or Russian letters, and Asian alphabets, are acceptable to use. Identifiers may include letters, digits, and underscores, but must always start with a letter. There are 73 reserved keywords in Ada that may not be used as identifiers, and these are:
======== ========= ========== ============
abort else null select
abs elsif of separate
abstract end or some
accept entry others subtype
access exception out synchronized
aliased exit overriding tagged
all for package task
and function pragma terminate
array generic private then
at goto procedure type
begin if protected until
body in raise use
case interface range when
constant is record while
declare limited rem with
delay loop renames xor
delta mod requeue
digits new return
do not reverse
======== ========= ========== ============
.. todo::
*Put the reserved words in bolface*
Ada is designed to be portable. Ada compilers must follow a precisely defined international (ISO) standard language specification with clearly documented areas of vendor freedom where the behavior depends on the implementation. It's possible, then, to write an implementation-independent application in Ada and to make sure it will have the same effect across platforms and compilers.
Ada is truly a general purpose, multiple paradigm language that allows the programmer to employ or avoid features like run-time contract checking, tasking, object oriented programming, and generics. Efficiently programmed Ada is employed in device drivers, interrupt handlers, and other low-level functions. It may be found today in devices with tight limits on processing speed, memory, and power consumption. But the language is also used for programming larger interconnected systems running on workstations, servers, and supercomputers.

View File

@@ -0,0 +1,81 @@
Compilation Unit Structure
**************************
C++ programming style usually promotes the use of two distinct files: header files used to define specifications (*.h*, *.hxx*, *.hpp*), and implementation files which contain the executable code (*.c*, *.cxx*, *.cpp*). However, the distinction between specification and implementation is not enforced by the compiler and may need to be worked around in order to implement, for example, inlining or templates.
Java compilers expect both the implementation and specification to be in the same *.java* file. (Yes, design patterns allow using interfaces to separate specification from implementation to a certain extent, but this is outside of the scope of this description.)
Ada is superficially similar to the C++ case: Ada compilation units are generally split into two parts, the specification and the body. However, what goes into those files is more predictable for both the compiler and for the programmer. With GNAT, compilation units are stored in files with a *.ads* extension for specifications and with a *.adb* extension for implementations.
Without further ado, we present the famous "Hello World" in three languages:
[Ada]
.. code-block:: ada
with Ada.Text_IO;
use Ada.Text_IO;
procedure Main is
begin
Put_Line ("Hello World");
end Main;
[C++]
.. code-block:: cpp
#include <iostream>
using namespace std;
int main(int argc, const char* argv[]) {
cout << "Hello World" << endl;
}
[Java]
.. code-block:: java
public class Main {
public static void main(String [] argv) {
System.out.println ("Hello World");
}
}
The first line of Ada we see is the **with** clause, declaring that the unit (in this case, the Main subprogram) will require the services of the package *Ada.Text_IO*. This is different from how **#include** works in C++ in that it does not, in a logical sense, copy/paste the code of *Ada.Text_IO* into *Main*. The **with** clause directs the compiler to make the public interface of the *Ada.Text_IO* package visible to code in the unit (here *Main*) containing the **with** clause. Note that this construct does not have a direct analog in Java, where the entire CLASSPATH is always accessible. Also, the name ''Main'' for the main subprogram was chosen for consistency with C++ and Java style but in Ada the name can be whatever the programmer chooses.
The **use** clause is the equivalent of **using namespace** in C++, or **import** in Java (though it wasn't necessary to use **import** in the Java example above). It allows you to omit the full package name when referring to **with**\ed units. Without the **use** clause, any reference to *Ada.Text_IO* items would have had to be fully qualified with the package name. The *Put_Line* line would then have read:
.. code-block:: ada
Ada.Text_IO.Put_Line ("Hello World");
The word "package" has different meanings in Ada and Java. In Java, a package is used as a namespace for classes. In Ada, it's often a compilation unit. As a result Ada tends to have many more packages than Java. Ada package specifications ("package specs" for short) have the following structure:
.. code-block:: ada
package Package_Name is
-- public declarations
private
-- private declarations
end Package_Name;
The implementation in a package body (written in a *.adb* file) has the structure:
.. code-block:: ada
package body Package_Name is
-- implementation
end Package_Name;
The **private** reserved word is used to mark the start of the private portion of a package spec. By splitting the package spec into private and public parts, it is possible to make an entity available for use while hiding its implementation. For instance, a common use is declaring a **record** (Ada's **struct**) whose fields are only visible to its package and not to the caller. This allows the caller to refer to objects of that type, but not to change any of its contents directly.
The package body contains implementation code, and is only accessible to outside code through declarations in the package spec.
An entity declared in the private part of a package in Ada is roughly equivalent to a protected member of a C++ or Java class. An entity declared in the body of an Ada package is roughly equivalent to a private member of a C++ or Java class.

View File

@@ -0,0 +1,68 @@
Low Level Programming
*********************
Representation Clauses
======================
We've seen in the previous chapters how Ada can be used to describe high level semantics and architecture. The beauty of the language, however, is that it can be used all the way down to the lowest levels of the development, including embedded assembly code or bit-level data management.
One very interesting feature of the language is that, unlike C, for example, there are no data representation constraints unless specified by the developer. This means that the compiler is free to choose the best trade-off in terms of representation vs. performance. Let's start with the following example:
[Ada]
.. code-block:: ada
type R is record
V : Integer range 0 .. 255;
B1 : Boolean;
B2 : Boolean;
end record
with Pack;
[C++]
.. code-block:: cpp
struct R {
unsigned int v:8;
bool b1;
bool b2;
};
[Java]
.. code-block:: java
public class R {
public byte v;
public boolean b1;
public boolean b2;
}
The Ada and the C++ code above both represent efforts to create an object that's as small as possible. Controlling data size is not possible in Java, but the language does specify the size of values for the primitive types.
Although the C++ and Ada code are equivalent in this particular example, there's an interesting semantic difference. In C++, the number of bits required by each field needs to be specified. Here, we're stating that *v* is only 8 bits, effectively representing values from 0 to 255. In Ada, it's the other way around: the developer specifies the range of values required and the compiler decides how to represent things, optimizing for speed or size. The **Pack** aspect declared at the end of the record specifies that the compiler should optimize for size even at the expense of decreased speed in accessing record components.
Other representation clauses can be specified as well, along with compile-time consistency checks between requirements in terms of available values and specified sizes. This is particularly useful when a specific layout is necessary; for example when interfacing with hardware, a driver, or a communication protocol. Here's how to specify a specific data layout based on the previous example:
.. code-block:: ada
type R is record
V : Integer range 0 .. 255;
B1 : Boolean;
B2 : Boolean;
end record;
for R use record
-- Occupy the first bit of the first byte.
B1 at 0 range 0 .. 0;
-- Occupy the last 7 bits of the first byte,
-- as well as the first bit of the second byte.
V at 0 range 1 .. 8;
-- Occupy the second bit of the second byte.
B2 at 1 range 1 .. 1;
end record;
We omit the **with** *Pack* directive and instead use a record representation clause following the record declaration. The compiler is directed to spread objects of type *R* across two bytes. The layout we're specifying here is fairly inefficient to work with on any machine, but you can have the compiler construct the most efficient methods for access, rather than coding your own machine-dependent bit-level methods manually.

View File

@@ -0,0 +1,40 @@
Embedded Assembly Code
======================
When performing low-level development, such as at the kernel or hardware driver level, there can be times when it is necessary to implement functionality with assembly code.
Every Ada compiler has its own conventions for embedding assembly code, based on the hardware platform and the supported assembler(s). Our examples here will work with GNAT and GCC on the x86 architecture.
All x86 processors since the Intel Pentium offer the *rdtsc* instruction, which tells us the number of cycles since the last processor reset. It takes no inputs and places an unsigned 64 bit value split between the *edx* and *eax* registers.
GNAT provides a subprogram called *System.Machine_Code.Asm* that can be used for assembly code insertion. You can specify a string to pass to the assembler as well as source-level variables to be used for input and output:
.. code-block:: ada
with System.Machine_Code; use System.Machine_Code;
with Interfaces; use Interfaces;
function Get_Processor_Cycles return Unsigned_64 is
Low, High : Unsigned_32;
Counter : Unsigned_64;
begin
Asm ("rdtsc",
Outputs =>
(Unsigned_32'Asm_Output ("=a", High),
Unsigned_32'Asm_Output ("=d", Low)),
Volatile => True);
Counter :=
Unsigned_64 (High) * 2 ** 32 +
Unsigned_64 (Low);
return Counter;
end Get_Processor_Cycles;
The *Unsigned_32'Asm_Output* clauses above provide associations between machine registers and source-level variables to be updated. "=a" and "=d" refer to the *eax* and *edx* machine registers, respectively. The use of the *Unsigned_32* and *Unsigned_64* types from package *Interfaces* ensures correct representation of the data. We assemble the two 32-bit values to form a single 64 bit value.
We set the *Volatile* parameter to *True* to tell the compiler that invoking this instruction multiple times with the same inputs can result in different outputs. This eliminates the possibility that the compiler will optimize multiple invocations into a single call.
With optimization turned on, the GNAT compiler is smart enough to use the *eax* and *edx* registers to implement the *High* and *Low* variables, resulting in zero overhead for the assembly interface.
The machine code insertion interface provides many features beyond what was shown here. More information can be found in the GNAT User's Guide, and the GNAT Reference manual.

View File

@@ -0,0 +1,47 @@
Interfacing with C
==================
Much effort was spent making Ada easy to interface with other languages. The *Interfaces* package hierarchy and the pragmas *Convention*, *Import*, and *Export* allow you to make inter-language calls while observing proper data representation for each language.
Let's start with the following C code:
.. code-block:: c
struct my_struct {
int A, B;
};
void call (my_struct * p) {
printf ("%d", p->A);
}
To call that function from Ada, the Ada compiler requires a description of the data structure to pass as well as a description of the function itself. To capture how the C **struct** *my_struct* is represented, we can use the following record along with a **pragma** *Convention*. The pragma directs the compiler to lay out the data in memory the way a C compiler would.
.. code-block:: ada
type my_struct is record
A : Interfaces.C.int;
B : Interfaces.C.int;
end record;
pragma Convention (C, my_struct);
Describing a foreign subprogram call to Ada code is called "binding" and it is performed in two stages. First, an Ada subprogram specification equivalent to the C function is coded. A C function returning a value maps to an Ada function, and a **void** function maps to an Ada procedure. Then, rather than implementing the subprogram using Ada code, we use a **pragma** *Import*:
.. code-block:: ada
procedure Call (V : my_struct);
pragma Import (C, Call, "call"); -- Third argument optional
The *Import* pragma specifies that whenever *Call* is invokeed by Ada code, it should invoke the *call* function with the C calling convention.
And that's all that's necessary. Here's an example of a call to *Call*:
.. code-block:: ada
declare
V : my_struct := (A => 1, B => 2);
begin
Call (V);
end;
You can also make Ada subprograms available to C code, and examples of this can be found in the GNAT User's Guide. Interfacing with C++ and Java use implementation-dependent features that are also available with GNAT.

View File

@@ -0,0 +1,8 @@
Conclusion
**********
All the usual paradigms of imperative programming can be found in all three languages that we surveyed in this document. However, Ada is different from the rest in that it's more explicit when expressing properties and expectations. This is a good thing: being more formal affords better communication among programmers on a team and between programmers and machines. You also get more assurance of the coherence of a program at many levels. Ada can help reduce the cost of software maintenance by shifting the effort to creating a sound system the first time, rather than working harder, more often, and at greater expense, to fix bugs found later in systems already in production. Applications that have reliability needs, long term maintenance requirements, or safety/security concerns are those for which Ada has a proven track record.
It's becoming increasingly common to find systems implemented in multiple languages, and Ada has standard interfacing facilities to allow Ada code to invoke subprograms and/or reference data structures from other language environments, or vice versa. Use of Ada thus allows easy interfacing between different technologies, using each for what it's best at.
We hope this guide has provided some insight into the Ada software engineer's world and has made Ada more accessible to programmers already familiar with programming in other languages.

View File

@@ -0,0 +1,6 @@
References
**********
The Ada Information Clearinghouse website http://www.adaic.org/learn/materials/, maintained by the Ada Resource Association, contains links to a variety of training materials (books, articles, etc.) that can help in learning Ada. The Development Center page http://www.adacore.com/knowledge on AdaCore's website also contains links to useful information including vides and tutorials on Ada.
The most comprehensive textbook is John Barnes' *Programming in Ada 2005*, which is oriented towards professional software developers.

View File

@@ -0,0 +1,90 @@
Statements and Declarations
===========================
The following code samples are all equivalent, and illustrate the use of comments and working with integer variables:
[Ada]
.. code-block:: ada
--
-- Ada program to declare and modify Integers
--
procedure Main is
-- Variable declarations
A, B : Integer := 0;
C : Integer := 100;
D : Integer;
begin
-- Ada uses a regular assignment statement for incrementation.
A := A + 1;
-- Regular addition
D := A + B + C;
end Main;
[C++]
.. code-block:: cpp
/*
* C++ program to declare and modify ints
*/
int main(int argc, const char* argv[]) {
// Variable declarations
int a = 0, b = 0, c = 100, d;
// C++ shorthand for incrementation
a++;
// Regular addition
d = a + b + c;
}
[Java]
.. code-block:: java
/*
* Java program to declare and modify ints
*/
public class Main {
public static void main(String [] argv) {
// Variable declarations
int a = 0, b = 0, c = 100, d;
// Java shorthand for incrementation
a++;
// Regular addition
d = a + b + c;
}
}
Statements are terminated by semicolons in all three languages. In Ada, blocks of code are surrounded by the reserved words **begin** and **end** rather than by curly braces. We can use both multi-line and single-line comment styles in the C++ and Java code, and only single-line comments in the Ada code.
Ada requires variable declarations to be made in a specific area called the *declarative part*, seen here before the **begin** keyword. Variable declarations start with the identifier in Ada, as opposed to starting with the type as in C++ and Java (also note Ada's use of the **:** separator). Specifying initializers is different as well: in Ada an initialization expression can apply to multiple variables (but will be evaluated separately for each), whereas in C++ and Java each variable is initialized individually. In all three languages, if you use a function as an initializer and that function returns different values on every invocation, each variable will get initialized to a different value.
Let's move on to the imperative statements. Ada does not provide **++** or ``--`` shorthand expressions for increment/decrement operations; it is necessary to use a full assignment statement. The **:=** symbol is used in Ada to perform value assignment. Unlike C++'s and Java's **=** symbol, **:=** can not be used as part of an expression. So, a statement like *A* **:=** *B* **:=** *C;* doesn't make sense to an Ada compiler, and neither does a clause like "**if** *A* **:=** *B* **then** ...." Both are compile-time errors.
You can nest a block of code within an outer block if you want to create an inner scope:
.. code-block:: ada
with Ada.Text_IO; use Ada.Text_IO;
procedure Main is
begin
Put_Line ("Before the inner block");
declare
Alpha : Integer := 0;
begin
Alpha := Alpha + 1;
Put_Line ("Now inside the inner block");
end;
Put_Line ("After the inner block");
end Main;
It is OK to have an empty declarative part or to omit the declarative part entirely---just start the inner block with **begin** if you have no declarations to make. However it is not OK to have an empty sequence of statements. You must at least provide a **null;** statement, which does nothing and indicates that the omission of statements is intentional.

View File

@@ -0,0 +1,103 @@
Conditions
==========
The use of the **if** statement:
[Ada]
.. code-block:: ada
if Variable > 0 then
Put_Line (" > 0 ");
elsif Variable < 0 then
Put_Line (" < 0 ");
else
Put_Line (" = 0 ");
end if;
[C++]
.. code-block:: cpp
if (Variable > 0)
cout << " > 0 " << endl;
else if (Variable < 0)
cout << " < 0 " << endl;
else
cout << " = 0 " << endl;
[Java]
.. code-block:: java
if (Variable > 0)
System.out.println (" > 0 ");
else if (Variable < 0)
System.out.println (" < 0 ");
else
System.out.println (" = 0 ");
In Ada, everything that appears between the **if** and **then** keywords is the conditional expression---no parentheses required. Comparison operators are the same, except for equality (**=**) and inequality (**/=**). The english words **not**, **and**, and **or** replace the symbols **!**, **&**, and **|**, respectively, for performing boolean operations.
It's more customary to use **&&** and **||** in C++ and Java than **&** and **|** when writing boolean expressions. The difference is that **&&** and **||** are short-circuit operators, which evaluate terms only as necessary, and **&** and **|** will unconditionally evaluate all terms. In Ada, **and** and **or** will evaluate all terms; **and then** and **or else** direct the compiler to employ short circuit evaluation.
Here are what switch/case statements look like:
[Ada]
.. code-block:: ada
case Variable is
when 0 =>
Put_Line ("Zero");
when 1 .. 9 =>
Put_Line ("Positive Digit");
when 10 | 12 | 14 | 16 | 18 =>
Put_Line ("Even Number between 10 and 18");
when others =>
Put_Line ("Something else");
end case;
[C++]
.. code-block:: cpp
switch (Variable) {
case 0:
cout << "Zero" << endl;
break;
case 1: case 2: case 3: case 4: case 5:
case 6: case 7: case 8: case 9:
cout << "Positive Digit" << endl;
break;
case 10: case 12: case 14: case 16: case 18:
cout << "Even Number between 10 and 18" << endl;
break;
default:
cout << "Something else";
}
[Java]
.. code-block:: java
switch (Variable) {
case 0:
System.out.println ("Zero");
break;
case 1: case 2: case 3: case 4: case 5:
case 6: case 7: case 8: case 9:
System.out.println ("Positive Digit");
break;
case 10: case 12: case 14: case 16: case 18:
System.out.println ("Even Number between 10 and 18");
break;
default:
System.out.println ("Something else");
}
In Ada, the **case** and **end case** lines surround the whole case statement, and each case starts with **when**. So, when programming in Ada, replace **switch** with **case**, and replace **case** with **when**.
Case statements in Ada require the use of discrete types (integers or enumeration types), and require all possible cases to be covered by **when** statements. If not all the cases are handled, or if duplicate cases exist, the program will not compile. The default case, **default:** in C++ and Java, can be specified using **when others =>** in Ada.
In Ada, the **break** instruction is implicit and program execution will never fall through to subsequent cases. In order to combine cases, you can specify ranges using **..** and enumerate disjoint values using **|** which neatly replaces the multiple **case** statements seen in the C++ and Java versions.

View File

@@ -0,0 +1,94 @@
Loops
=====
In Ada, loops always start with the **loop** reserved word and end with **end loop**. To leave the loop, use **exit**---the C++ and Java equivalent being **break**. This statement can specify a terminating condition using the **exit when** syntax. The **loop** opening the block can be preceded by a **while** or a **for**.
The **while** loop is the simplest one, and is very similar across all three languages:
[Ada]
.. code-block:: ada
while Variable < 10_000 loop
Variable := Variable * 2;
end loop;
[C++]
.. code-block:: cpp
while (Variable < 10000) {
Variable = Variable * 2;
}
[Java]
.. code-block:: java
while (Variable < 10000) {
Variable = Variable * 2;
}
Ada's **for** loop, however, is quite different from that in C++ and Java. It always increments or decrements a loop index within a discrete range. The loop index (or "loop parameter" in Ada parlance) is local to the scope of the loop and is implicitly incremented or decremented at each iteration of the loop statements; the program cannot directly modify its value. The type of the loop parameter is derived from the range. The range is always given in ascending order even if the loop iterates in descending order. If the starting bound is greater than the ending bound, the interval is considered to be empty and the loop contents will not be executed. To specify a loop iteration in decreasing order, use the **reverse** reserved word. Here are examples of loops going in both directions:
[Ada]
.. code-block:: ada
-- Outputs 0, 1, 2, ..., 9
for Variable in 0 .. 9 loop
Put_Line (Integer'Image (Variable));
end loop;
-- Outputs 9, 8, 7, ..., 0
for Variable in reverse 0 .. 9 loop
Put_Line (Integer'Image (Variable));
end loop;
[C++]
.. code-block:: cpp
// Outputs 0, 1, 2, ..., 9
for (int Variable = 0; Variable <= 9; Variable++) {
cout << Variable << endl;
}
// Outputs 9, 8, 7, ..., 0
for (int Variable = 9; Variable >=0; Variable--) {
cout << Variable << endl;
}
[Java]
.. code-block:: java
// Outputs 0, 1, 2, ..., 9
for (int Variable = 0; Variable <= 9; Variable++) {
System.out.println (Variable);
}
// Outputs 9, 8, 7, ..., 0
for (int Variable = 9; Variable >= 0; Variable--) {
System.out.println (Variable);
}
Ada uses the *Integer* type's *'Image* attribute to convert a numerical value to a String. There is no implicit conversion between *Integer* and *String* as there is in C++ and Java. We'll have a more in-depth look at such attributes later on.
It's easy to express iteration over the contents of a container (for instance, an array, a list, or a map) in Ada and Java. For example, assuming that *Int_List* is defined as an array of Integer values, you can use:
[Ada]
.. code-block:: ada
for I of Int_List loop
Put_Line (Integer'Image (I));
end loop;
[Java]
.. code-block:: java
for (int i : Int_List) {
System.out.println (i);
}

View File

@@ -0,0 +1,50 @@
Strong Typing
=============
One of the main characteristics of Ada is its strong typing (i.e., relative absence of implicit type conversions). This may take some getting used to. For example, you can't divide an integer by a float. You need to perform the division operation using values of the same type, so one value must be explicitly converted to match the type of the other (in this case the more likely conversion is from integer to float). Ada is designed to guarantee that what's done by the program is what's meant by the programmer, leaving as little room for compiler interpretation as possible. Let's have a look at the following example:
[Ada]
.. code-block:: ada
procedure Strong_Typing is
Alpha : Integer := 1;
Beta : Integer := 10;
Result : Float;
begin
Result := Float (Alpha) / Float (Beta);
end Strong_Typing;
[C++]
.. code-block:: cpp
void weakTyping (void) {
int alpha = 1;
int beta = 10;
float result;
result = alpha / beta;
}
[Java]
.. code-block:: java
void weakTyping () {
int alpha = 1;
int beta = 10;
float result;
result = alpha / beta;
}
Are the three programs above equivalent? It may seem like Ada is just adding extra complexity by forcing you to make the conversion from Integer to Float explicit. In fact it significantly changes the behavior of the computation. While the Ada code performs a floating point operation **1.0 / 10.0** and stores 0.1 in *Result*, the C++ and Java versions instead store 0.0 in *result*. This is because the C++ and Java versions perform an integer operation between two integer variables: **1 / 10** is **0**. The result of the integer division is then converted to a *float* and stored. Errors of this sort can be very hard to locate in complex pieces of code, and systematic specification of how the operation should be interpreted helps to avoid this class of errors. If an integer division was actually intended in the Ada case, it is still necessary to explicitly convert the final result to *Float*:
.. code-block:: ada
-- Perform an Integer division then convert to Float
Result := Float (Alpha / Beta);
In Ada, a floating point literal must be written with both an integral and decimal part. **10** is not a valid literal for a floating point value, while **10.0** is.

View File

@@ -0,0 +1,4 @@
Language-Defined Types
======================
The principal scalar types predefined by Ada are *Integer*, *Float*, *Boolean*, and *Character*. These correspond to **int**, **float**, **bool**/**boolean**, and **char**, respectively. The names for these types are not reserved words; they are regular identifiers.

View File

@@ -0,0 +1,97 @@
Application-Defined Types
=========================
Ada's type system encourages programmers to think about data at a high level of abstraction. The compiler will at times output a simple efficient machine instruction for a full line of source code (and some instructions can be eliminated entirely). The careful programmer's concern that the operation really makes sense in the real world would be satisfied, and so would the programmer's concern about performance.
The next example below defines two different metrics: area and distance. Mixing these two metrics must be done with great care, as certain operations do not make sense, like adding an area to a distance. Others require knowledge of the expected semantics; for example, multiplying two distances. To help avoid errors, Ada requires that each of the binary operators "+", "-", "*", and "/" for integer and floating-point types take operands of the same type and return a value of that type.
.. code-block:: ada
procedure Main is
type Distance is new Float;
type Area is new Float;
D1 : Distance := 2.0;
D2 : Distance := 3.0;
A : Area;
begin
D1 := D1 + D2; -- OK
D1 := D1 + A; -- NOT OK: incompatible types for "+" operator
A := D1 * D2; -- NOT OK: incompatible types for ":=" assignment
A := Area (D1 * D2); -- OK
end Main;
Even though the **Distance** and **Area** types above are just **Float**\s, the compiler does not allow arbitrary mixing of values of these different types. An explicit conversion (which does not necessarily mean any additional object code) is necessary.
The predefined Ada rules are not perfect; they admit some problematic cases (for example multiplying two **Distance**\s yields a **Distance**) and prohibit some useful cases (for example multiplying two **Distance**\s should deliver an **Area**). These situations can be handled through other mechanisms. A predefined operation can be identified as **abstract** to make it unavailable; overloading can be used to give new interpretations to existing operator symbols, for example allowing an operator to return a value from a type different from its operands; and more generally, GNAT has introduced a facility that helps perform dimensionality checking.
Ada enumerations work similarly to C++ and Java's *enum*\s.
[Ada]
.. code-block:: ada
type Day is
(Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday,
Sunday);
[C++]
.. code-block:: cpp
enum Day {
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday,
Sunday};
[Java]
.. code-block:: java
enum Day {
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday,
Sunday}
But even though such enumerations may be implemented using a machine word, at the language level Ada will not confuse the fact that *Monday* is a *Day* and is not an *Integer*. You can compare a *Day* with another *Day*, though. To specify implementation details like the numeric values that correspond with enumeration values in C++ you include them in the original *enum* statement:
[C++]
.. code-block:: cpp
enum Day {
Monday = 10,
Tuesday = 11,
Wednesday = 12,
Thursday = 13,
Friday = 14,
Saturday = 15,
Sunday = 16};
But in Ada you must use both a type definition for *Day* as well as a separate *representation clause* for it like:
[Ada]
.. code-block:: ada
for Day use
(Monday => 10,
Tuesday => 11,
Wednesday => 12,
Thursday => 13,
Friday => 14,
Saturday => 15,
Sunday => 16);

View File

@@ -0,0 +1,47 @@
Type Ranges
===========
Contracts can be associated with types and variables, to refine values and define what are considered valid values. The most common kind of contract is a *range constraint* introduced with the **range** reserved word, for example:
.. code-block:: ada
procedure Main is
type Grade is range 0 .. 100;
G1, G2 : Grade;
N : Integer;
begin
... -- Initialization of N
G1 := 80; -- OK
G1 := N; -- Illegal (type mismatch)
G1 := Grade (N); -- Legal, run-time range check
G2 := G1 + 10; -- Legal, run-time range check
G1 := (G1 + G2)/2; -- Legal, run-time range check
end Main;
In the above example, *Grade* is a new integer type associated with a range check. Range checks are dynamic and are meant to enforce the property that no object of the given type can have a value outside the specified range. In this example, the first assignment to *G1* is correct and will not raise a run-time exceprion. Assigning *N* to *G1* is illegal since *Grade* is a different type than *Integer*. Converting *N* to *Grade* makes the assignment legal, and a range check on the conversion confirms that the value is within 0 .. 100. Assigning *G1+10* to *G2* is legal since **+** for *Grade* returns a *Grade* (note that the literal *10* is interpreted as a *Grade* value in this context), and again there is a range check.
The final assignment illustrates an interesting but subtle point. The subexpression *G1 + G2* may be outside the range of *Grade*, but the final result will be in range. Nevertheless, depending on the representation chosen for *Grade*, the addition may overflow. If the compiler represents *Grade* values as signed 8-bit integers (i.e., machine numbers in the range -128 .. 127) then the sum *G1+G2* may exceed 127, resulting in an integer overflow. To prevent this, you can use explicit conversions and perform the computation in a sufficiently large integer type, for example:
.. code-block:: ada
G1 := Grade (Integer (G1) + Integer (G2)) / 2);
Range checks are useful for detecting errors as early as possible. However, there may be some impact on performance. Modern compilers do know how to remove redundant checks, and you can deactivate these checks altogether if you have sufficient confidence that your code will function correctly.
Types can be derived from the representation of any other type. The new derived type can be associated with new constraints and operations. Going back to the *Day* example, one can write:
.. code-block:: ada
type Business_Day is new Day range Monday .. Friday;
type Weekend_Day is new Day range Saturday .. Sunday;
Since these are new types, implicit conversions are not allowed. In this case, it's more natural to create a new set of constraints for the same type, instead of making completely new ones. This is the idea behind `subtypes' in Ada. A subtype is a type with optional additional constraints. For example:
.. code-block:: ada
subtype Business_Day is Day range Monday .. Friday;
subtype Weekend_Day is Day range Saturday .. Sunday;
subtype Dice_Throw is Integer range 1 .. 6;
These declarations don't create new types, just new names for constrained ranges of their base types.

View File

@@ -0,0 +1,22 @@
Generalized Type Contracts: Subtype Predicates
==============================================
Range checks are a special form of type contracts; a more general method is provided by Ada subtype predicates, introduced in Ada 2012. A subtype predicate is a boolean expression defining conditions that are required for a given type or subtype. For example, the *Dice_Throw* subtype shown above can be defined in the following way:
.. code-block:: ada
subtype Dice_Throw is Integer
with Dynamic_Predicate => Dice_Throw in 1 .. 6;
The clause beginning with **with** introduces an Ada `aspect', which is additional information provided for declared entities such as types and subtypes. The *Dynamic_Predicate* aspect is the most general form. Within the predicate expression, the name of the (sub)type refers to the current value of the (sub)type. The predicate is checked on assignment, parameter passing, and in several other contexts. There is a "Static_Predicate" form which introduce some optimization and constrains on the form of these predicates, outside of the scope of this document.
Of course, predicates are useful beyond just expressing ranges. They can be used to represent types with arbitrary constraints, in particular types with discontinuities, for example:
.. code-block:: ada
type Not_Null is new Integer
with Dynamic_Predicate => Not_Null /= 0;
type Even is new Integer
with Dynamic_Predicate => Even mod 2 = 0;

View File

@@ -0,0 +1,55 @@
Attributes
==========
Attributes start with a single apostrophe ("tick"), and they allow you to query properties of, and perform certain actions on, declared entities such as types, objects, and subprograms. For example, you can determine the first and last bounds of scalar types, get the sizes of objects and types, and convert values to and from strings. This section provides an overview of how attributes work. For more information on the many attributes defined by the language, you can refer directly to the Ada Language Reference Manual.
The *'Image* and *'Value* attributes allow you to transform a scalar value into a *String* and vice-versa. For example:
.. code-block:: ada
declare
A : Integer := 99;
begin
Put_Line (Integer'Image (A));
A := Integer'Value ("99");
end;
Certain attributes are provided only for certain kinds of types. For example, the *'Val* and *'Pos* attributes for an enumeration type associates a discrete value with its position among its peers. One circuitous way of moving to the next character of the ASCII table is:
[Ada]
.. code-block:: ada
declare
C : Character := 'a';
begin
C := Character'Val (Character'Pos (C) + 1);
end;
A more concise way to get the next value in Ada is to use the *'Succ* attribute:
.. code-block:: ada
declare
C : Character := 'a';
begin
C := Character'Succ (C);
end;
You can get the previous value using the *'Pred* attribute. Here is the equivalent in C++ and Java:
[C++]
.. code-block:: cpp
char c = 'a';
c++;
[Java]
.. code-block:: java
char c = 'a';
c++;
Other interesting examples are the *'First* and *'Last* attributes which, respectively, return the first and last values of a scalar type. Using 32-bit integers, for instance, *Integer'First* returns -2\ :superscript:`31` and *Integer'Last* returns 2\ :superscript:`31` - 1.

View File

@@ -0,0 +1,176 @@
Arrays and Strings
==================
C++ arrays are pointers with offsets, but the same is not the case for Ada and Java. Arrays in the latter two languages are not interchangable with operations on pointers, and array types are considered first-class citizens. Arrays in Ada have dedicated semantics such as the availability of the array's boundaries at run-time. Therefore, unhandled array overflows are impossible unless checks are suppressed. Any discrete type can serve as an array index, and you can specify both the starting and ending bounds---the lower bound doesn't necessarily have to be 0. Most of the time, array types need to be explicitly declared prior to the declaration of an object of that array type.
Here's an example of declaring an array of 26 characters, initializing the values from 'a' to 'z':
[Ada]
.. code-block:: ada
declare
type Arr_Type is array (Integer range <>) of Character;
Arr : Arr_Type (1 .. 26);
C : Character := 'a';
begin
for I in Arr'Range loop
Arr (I) := C;
C := Character'Succ (C);
end loop;
end;
[C++]
.. code-block:: cpp
char Arr [26];
char C = 'a';
for (int I = 0; I < 26; ++I) {
Arr [I] = C;
C = C + 1;
}
[Java]
.. code-block:: java
char [] Arr = new char [26];
char C = 'a';
for (int I = 0; I < Arr.length; ++I) {
Arr [I] = C;
C = C + 1;
}
In C++ and Java, only the size of the array is given during declaration. In Ada, array index ranges are specified using two values of a discrete type. In this example, the array type declaration specifies the use of Integer as the index type, but does not provide any constraints (use <>, pronounced `box', to specify "no constraints"). The constraints are defined in the object declaration to be 1 to 26, inclusive. Arrays have an attribute called *'Range*. In our example, *Arr'Range* can also be expressed as *Arr'First .. Arr'Last*; both expressions will resolve to *1 .. 26*. So the *'Range* attribute supplies the bounds for our **for** loop. There is no risk of stating either of the bounds incorrectly, as one might do in C++ where "I <= 26" may be specified as the end-of-loop condition.
As in C++, Ada *String*\s are arrays of *Character*\s. The C++ or Java *String* class is the equivalent of the Ada type *Ada.Strings.Unbounded_String* which offers additional capabilities in exchange for some overhead. Ada strings, importantly, are not delimited with the special character '\\0' like they are in C++. It is not necessary because Ada uses the array's bounds to determine where the string starts and stops.
Ada's predefined *String* type is very straighforward to use:
.. code-block:: ada
My_String : String (1 .. 26);
Unlike C++ and Java, Ada does not offer escape sequences such as '\\n'. Instead, explicit values from the *ASCII* package must be concatenated (via the concatenation operator, &). Here for example, is how to initialize a line of text ending with a new line:
My_String : String := "This is a line with a end of line" & ASCII.LF;
You see here that no constraints are necessary for this variable definition. The initial value given allows the automatic determination of *My_String*'s bounds.
Ada offers high-level operations for copying, slicing, and assigning values to arrays. We'll start with assignment. In C++ or Java, the assignment operator doesn't make a copy of the value of an array, but only copies the address or reference to the target variable. In Ada, the actual array contents are duplicated. To get the above behavior, actual pointer types would have to be defined and used.
[Ada]
.. code-block:: ada
declare
type Arr_Type is array (Integer range <>) of Integer
A1 : Arr_Type (1 .. 2);
A2 : Arr_Type (1 .. 2);
begin
A1 (1) = 0;
A1 (2) = 1;
A2 := A1;
end;
[C++]
.. code-block:: cpp
int A1 [2];
int A2 [2];
A1 [0] = 0;
A1 [1] = 1;
for (int i = 0; i < 2; ++i) {
A2 [i] = A1 [i];
}
[Java]
.. code-block:: java
int [] A1 = new int [2];
int [] A2 = new int [2];
A1 [0] = 0;
A1 [1] = 1;
A2 = Arrays.copyOf(A1, A1.length);
In all of the examples above, the source and destination arrays must have precisely the same number of elements. Ada allows you to easily specify a portion, or slice, of an array. So you can write the following:
[Ada]
.. code-block:: ada
declare
type Arr_Type is array (Integer range <>) of Integer
A1 : Arr_Type (1 .. 10);
A2 : Arr_Type (1 .. 5);
begin
A2 (1 .. 3) := A1 (4 .. 6);
end;
This assigns the 4th, 5th, and 6th elements of *A1* into the 1st, 2nd, and 3rd elements of *A2*. Note that only the length matters here: the values of the indexes don't have to be equal; they slide automatically.
Ada also offers high level comparison operations which compare the contents of arrays as opposed to their addresses:
[Ada]
.. code-block:: ada
declare
type Arr_Type is array (Integer range <>) of Integer;
A1 : Arr_Type (1 .. 2);
A2 : Arr_Type (1 .. 2);
begin
if A1 = A2 then
[C++]
.. code-block:: cpp
int A1 [2];
int A2 [2];
bool eq = true;
for (int i = 0; i < 2; ++i) {
if (A1 [i] != A2 [i]) {
eq = false;
}
}
if (eq) {
[Java]
.. code-block:: java
int [] A1 = new int [2];
int [] A2 = new int [2];
if (A1.equals (A2)) {
You can assign to all the elements of an array in each language in different ways. In Ada, the number of elements to assign can be determined by looking at the right-hand side, the left-hand side, or both sides of the assignment. When bounds are known on the left-hand side, it's possible to use the **others** expression to define a default value for all the unspecified array elements. Therefore, you can write:
.. code-block:: ada
declare
type Arr_Type is array (Integer range <>) of Integer;
A1 : Arr_Type := (1, 2, 3, 4, 5, 6, 7, 8, 9);
A2 : Arr_Type (-2 .. 42) := (others => 0);
begin
A1 := (1, 2, 3, others => 10);
-- use a slice to assign A2 elements 11 .. 19 to 1
A2 (11 .. 19) := (others => 1);
end;

View File

@@ -0,0 +1,58 @@
Heterogeneous Data Structures
=============================
In Ada, there's no distinction between **struct** and **class** as there is in C++. All heterogeneous data structures are **record**\s. Here are some simple records:
[Ada]
.. code-block:: ada
declare
type R is record
A, B : Integer;
C : Float;
end record;
V : R;
begin
V.A := 0;
end;
[C++]
.. code-block:: cpp
struct R {
int A, B;
float C;
};
R V;
V.A = 0;
[Java]
.. code-block:: java
class R {
public int A, B;
public float C;
}
R V = new R ();
V.A = 0;
Ada allows specification of default values for fields just like C++ and Java. The values specified can take the form of an ordered list of values, a named list of values, or an incomplete list followed by **others** => <> to specify that fields not listed will take their default values. For example:
.. code-block:: ada
type R is record
A, B : Integer := 0;
C : Float := 0.0;
end record;
V1 : R => (1, 2, 1.0);
V2 : R => (A => 1, B => 2, C => 1.0);
V3 : R => (C => 1.0, A => 1, B => 2);
V3 : R => (C => 1.0, others => <>);

Some files were not shown because too many files have changed in this diff Show More