Assessments

· Multiple-Choice Quiz 1

1.3.1 Data Types Fundamental Data Types As in most other programming languages including Java, C++ categorizes data objects into different types. These different data types describe not only the fundamental operations that the language performs on the data, but also the range of values that the data types accept. Since different data types have different allowable values, the language can check to ensure that a programmer only assigns appropriate values to a data object. An error occurs if a programmer assigns an inappropriate value, such as a number that is too large or too small, to a data object. This mechanism is known as type checking. C++ is considered a strongly typed language since it is very strict about checking data types and their corresponding values. In the end, this is good for the C++ programmer, since strongly typed languages can detect errors that other languages may not detect. The fundamental data types that C++ supports are similar to the primitive data types of Java. The following table lists each of the fundamental data types of C++ and the corresponding Java primitive data type. 1.3.1 Data Types Fundamental Data Types   Типы данных описывают не только фундаментальные операции, но также диапазон значений, которые принимают типы данных. Так как у различных типов данных различен диапазон значений, язык программирования предоставляет возможность проверить соответствующее значение объекта данных. Ошибка возникает, если только целому числу присвоят значение слишком большое или слишком маленькое. Этот механизм известен как проверка типа. Он позволяет обнаружить ошибки, которые, возможно, не обнаруживаются в других языках программирования. В C++ фундаментальные типы данных подобны типам данных Java. Следующая таблица представляет фундаментальные типы данных в C++ и соответствующие им тип данных в Java.
C++ type Java type     Table 1 C++ and Java data types
bool boolean
char char
int int
short short
long long
float float
double double

 

The space required to store variables differs across languages. In C++, the storage space requirements are left to the discretion of the compiler implementers. Unlike Java, these requirements are not specifically stated by the language standard. Therefore, on one platform a C++ int may be two bytes long, while on another it may be four bytes long. But, in Java, a variable of type int is guaranteed to require four bytes of memory to store. Usually, the size in bytes of a variable is unimportant, except that it dictates the range of values that a variable can accept. As the number of bytes that a language implementation uses to store a variable increases, so does the range of values that the variable accepts. The following example program uses the C++ sizeof operator to display the size, in bytes, of the fundamental data types of the particular C++ implementation used in В C++ место хранения данных в памяти определяется конструктором компилятора. В Java, эти требования не требуют какого либо указания. Поэтому в C++ int может быть длиной как два так и четыре байта. В Java же переменная типа int всегда равна длине памяти в четыре байта. Размер в байтах незначителен, за исключением того, что он диктует диапазон значений, которые может принять переменная.   Следующая программа в C++ качестве примера использует оператор sizeof, чтобы показать размер, в байтах, фундаментальных типов специфических данных в C++, используемое в компиляции при выполнении.
1: 2: 3: 4: 5: 6: 7: 8: 9: 10: 11: 12: 13: 14: #include <cstdlib>#include <iostream> using namespace std; int main(int argc, char* argv[]) { cout << " bool: " << sizeof(bool) << endl; cout << " char: " << sizeof(char) << endl; cout << " short: " << sizeof(short) << endl; cout << " int: " << sizeof(int) << endl; cout << " long: " << sizeof(long) << endl; cout << " float: " << sizeof(float) << endl; cout << "double: " << sizeof(double) << endl; return EXIT_SUCCESS;} Listing 1 Data types and the sizeof operator
 

 

Like Java, C++ contains a mechanism to create "read-only" variables. C++ uses the keyword const to allow programmers to create "read-only" variables. This keyword signals that the variable being declared cannot be modified after it is initialized. The keyword const of C++ is analogous to the keyword final in Java. Listing 2 shows the declaration and initialization of some "read-only" variables, otherwise simply known as "constant variables" or just "constants."
1: 2: 3: const int BOILING_POINT = 100;const int FREEZING_POINT = 0;const float PI = 3.14159;
Listing 2 Constant variables