Creating New Data Type Names

It is possible in C++ for a programmer to create additional names for existing data types. Creating another name uses the keyword typedef. The syntax to create a new name is as follows.

typedef type-expression new-name;

Example 1 Usage of typedef

The following listing contains a few examples of the use of the keyword typedef.

1: 2: 3: 4: 5: 6: 7: 8: 9: 10: 11: 12: 13: 14: 15: 16: 17: #include <iostream>#include <cstdlib> using namespace std; typedef int my_int;typedef my_int* my_int_ptr; int main(int argc, char* argv[]) { my_int i = 10; my_int_ptr ptr = &i; cout << *ptr << endl; return EXIT_SUCCESS;}
Listing 8 A sample use of typedef

Using data type names created with typedef allows programmers to encapsulate their choice of data types. This is good programming practice, since, if the need arises, a programmer can easily change all uses of a particular data type simply by changing the definition of the typedef. Additional benefits of the use of typedef will be examined in 1.5.3 Templates.

В C++ существует некоторая опасность – отсутствие проверки конца (границы) массива. Дело в том, что в C++ граничная проверка массива не поддержана. Если у нас есть массив из десяти элементов, то в C++, мы можем попытаться получить доступ к 12-ому, к 20-ому, или даже 100-ому индексу. Но мы можем убедиться, однако, что данные, которые мы получаем из за пределов массива не будут значащими. Следующая распечатка показывает выход за пределы массива в C ++.

1: 2: int arr[10];cout << arr[11] << endl;
Listing 7 Out of bounds access

Код в вышеупомянутой распечатке, в контексте фактической программы определенно компилируется, и это даже может работать без ошибки. Несомненно это опасная практика, и то,что нам следует всегда избегать.