рефераты конспекты курсовые дипломные лекции шпоры

Реферат Курсовая Конспект

An Example: Assumption Verification

An Example: Assumption Verification - раздел Философия, Data Structures and Algorithms in C++ Verifying Assumptions Using Assertions Is An Example Of A Common Use Of The P...

Verifying assumptions using assertions is an example of a common use of the preprocessor and its features. An assertion is a statement placed in source code to verify an assumption. Usually, programmers place assertions at the beginning of a function definition to verify assumptions they made when designing the function. If at run-time the assumption proves to be incorrect, the assert statement displays a notification message and stops the execution of the program. Used in this manner, assertions are an excellent tool for error detection.

All kinds of assumptions are made in programs about the data contained in variables, especially those found in parameters being passed to a function. When we design and code a function, we expect the parameters to contain valid data. If the parameters do not contain valid data, this could signify that an error exists in some other area of the program. Coding around the invalid data only serves to hide the error, whereas using an assertion can detect and point out the existence of that error.

Consider the function calculate_average that calculates the average of a series of values. We assume the caller of the function passes two non-zero integer parameters to the function. In the context of a larger program, if the second parameter were passed as zero, a run-time error would occur as a result of the divide-by-zero. How can we handle this invalid data? One way, seen in Listing 6, involves coding defensively to detect the invalid data case.

1: 2: 3: 4: 5: 6: 7: 8: 9: 10: double calculate_average(int total, int count) { // avoid divide by zero error if (count != 0) { return total / count; } else { return 0; }}
Listing 6 Defensive coding

The above version of calculate_average works in that it prevents the divide-by-zero error. It does not take into consideration that a zero count could mean that an error occurred in another part of the program. Perhaps a bug exists in the code that reads the values from the user. Or, maybe some other code erroneously overwrote the value of count. We really do not know, but using this version of calculate_average will not help us detect and locate this error.

The following version of calculate_average takes a different approach. Here, the assumption of valid data is verified using an assertion. If the caller of the function passes invalid data (that is, count equals zero) to the function, the assertion displays an error message and stops program execution. The programmer can then find the error that caused the passing of invalid data to function calculate_average.

1: 2: 3: 4: 5: 6: 7: double calculate_average(int total, int count) { // assume we are given valid data assert (count != 0); return total / count;}
Listing 7 Verifying an assumption using an assertion

The assert statement actually is a macro. Contained in library <cassert>, this macro definition is a little complex, but worth examining since it incorporates a few different uses of the preprocessor. The following example lists the definition of the assert macro from a GNU C++ compiler.

1: 2: 3: 4: 5: 6: 7: 8: 9: 10: 11: 12: 13: 14: 15: 16: 17: 18: 19: 20: 21: 22: 23: 24: 25: 26: 27: 28: 29: /* assert.h*/ #ifdef __cplusplusextern "C" {#endif #include "_ansi.h" #undef assert #ifdef NDEBUG /* required by ANSI standard */#define assert(p) ((void)0)#else #ifdef __STDC__#define assert(e) ((e) ? (void)0 : __assert(__FILE__, __LINE__, #e))#else /* PCC */#define assert(e) ((e) ? (void)0 : __assert(__FILE__, __LINE__, "e"))#endif #endif /* NDEBUG */ void _EXFUN(__assert, (const char *, int, const char *)); #ifdef __cplusplus}#endif
Listing 8 The assert macro definition

Notice the use of conditional compilation in the definition of the assert macro. Including a definition of NDEBUG into a program would disable all the assertion checks. When releasing production versions of software, programmers typically remove assertions.

– Конец работы –

Эта тема принадлежит разделу:

Data Structures and Algorithms in C++

Compiling and Running a C Program C Background History C is a modern object oriented programming language that supports... Table Different problems with similar solutions Each of the problems... Vectors...

Если Вам нужно дополнительный материал на эту тему, или Вы не нашли то, что искали, рекомендуем воспользоваться поиском по нашей базе работ: An Example: Assumption Verification

Что будем делать с полученным материалом:

Если этот материал оказался полезным ля Вас, Вы можете сохранить его на свою страничку в социальных сетях:

Все темы данного раздела:

Assessments
· Multiple-Choice Quiz 1 Recommended Exercise 1 1.3.1 Data Types Fundamental Data Types As in most other programming languages including Java, C+

Strings
In C++, the string data type provides the necessary abstraction to allow C++ programmers to work with character strings. The Java counterpart is actually two separate classes. Unlike its J

Strings
В C ++, тип данных string обеспечивает необходимую абстракцию, чтобы позволить программистам работать со строками символов. В Java фактически образуют два отдельных класса. В отличие от Ja

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

Создание новых имен типов данных.
В C++ есть возможность создать дополнительно к существующим собственные типы данных с новым именем. Для этого необходимо использовать ключевое слово typedef. Синтаксис, чтобы создать новое имя след

Constructors
Constructors are the methods of a class that define what actions to take when creating an object. A C++ class can have multiple constructors. This allows variation in object instantiation since dif

The Destructor
A destructor is a special member function of a C++ class called when an object's lifetime ends. Like a copy constructor, only one destructor can exist for a class. Since they execute when an object

Declaration vs. Definition
In this discussion on the specification of classes in C++, the term "definition" has been used regarding functions. When we "define" a function, we dictate the function's behavi

Basic Syntax
Класс - основная единица абстракции в C++. Давайте сначала рассмотрим простой класс, определенный в Java, и затем соответствующую версию в C++. ………………………………………………………………………………… Сле

Constructors
Конструктор создает и инициализирует новый экземпляр класса. В C++ класс может иметь несколько конструкторов. Это позволяет вносить изменение в экземпляры класса включая типы параметров и значения,

Declaration vs. Definition
В обсуждении о спецификации классов, термин "definition" ("определение") был использован относительно функции. Когда мы "definition" функцию, мы определяем поведение ф

Streams
Input and output in C++ is based on the concept of a stream. A stream is a sequence of bytes that flow from something to something else. The process of output involves moving bytes, one at a time,

Using the Standard Streams
Three specific streams are always available throughout the lifetime of every C++ program. These are the standard input, standard output, and standard error streams. Each of these standard streams h

File Input and Output
File based input and output is similar to the mechanisms for keyboard and screen I/O. The main difference is that programmers must explicitly open and close files. In pseudocode, a generic program

Some Common Pitfalls
  A common mistake for many new C++ programmers is to reverse the << and >> operators. A good way to remember which operator to use is to think of them as arrows. You alwa

Streams
Ввод и вывод в C ++ основан на понятии потока. Поток - последовательность байтов, которые вытекают из одного в другое. Процесс продукции вовлекает байты, по одному, с программы на устройство. Это у

Using the Standard Streams
Три определенных потока всегда доступны всюду в C ++ программах. Это standard input, standard output, and standard error потоки. У каждого из этих стандартных потоков есть определенное использовани

File Input and Output
Файл вход и выход подобен механизмам для ввода / вывода экрана и клавиатуры. Главное различие - то, что программисты должны явно открыть и закрыть файлы. В псевдокоде главная программа, которая чит

Some Common Pitfalls
Частая ошибка для многих новых C ++ программисты состоит в том, чтобы полностью изменить << и >> операторы. Хороший способ помнить, какой оператор использовать должен думать о них как о

Text Substitution
The preprocessor is a tool that C++ programmers use to manipulate the contents of source code files prior to compilation. In the most general sense, the preprocessor performs text substitution and

File Inclusion
File inclusion is a feature of the C++ preprocessor that allows a source code file to use shared code. We consider shared code to be classes or functions declared in other files. In C++, we can onl

Macro Substitution
The C++ preprocessor can perform a programmer defined text substitution throughout an entire source code file. This is known as macro substitution. Programmers define a macro using the #define prep

Conditional Compilation
Beyond macro substitution, a more important reason to use #define is to support conditional compilation. Using #define, and some other preprocessor directives, we can instruct the compiler to compi

Text Substitution
Препроцессор это инструмент, чтобы управлять содержанием файлов исходного текста до компиляции. В самом общем смысле препроцессор выполняет текстовую замену и текстовую модификацию. Высокоуровневые

File Inclusion
Включение файла - особенность C++ препроцессор, который позволяет файлу исходного текста использовать разделенные коды. Мы полагаем, что разделенный код это классы или функции, объявленные в других

Macro Substitution
C++ препроцессор может определить текстовую замену всюду по всему файлу исходного текста. Это известно как макро-замена. Программисты реализуют макро-замену директивой #define препроцессора, котора

Conditional Compilation
Вне макро-замены важная причина использовать #define состоит в том, чтобы поддержать условную трансляцию. Используя #define, и некоторые другие директивы препроцессора, мы можем проинструктировать

An Example: Assumption Verification
Подтверждение предположений, используя утверждения является примером обычного использования препроцессора и его особенностей. assertion - утверждение, помещенное в исходный текст, чтобы проверить п

Хотите получать на электронную почту самые свежие новости?
Education Insider Sample
Подпишитесь на Нашу рассылку
Наша политика приватности обеспечивает 100% безопасность и анонимность Ваших E-Mail
Реклама
Соответствующий теме материал
  • Похожее
  • Популярное
  • Облако тегов
  • Здесь
  • Временно
  • Пусто
Теги