标签:des style blog http color io os 使用 java
In computer programming, an assertion is a predicate (a true–false statement) placed in a program to indicate that the developer thinks that the predicate is always true at that place. If an assertion evaluates to false at run-time, an assertion failure results, which typically causes execution to abort.
在程式設計中,斷言(assertion)是一種放在程式中的一階邏輯(如一個結果為真或是假的邏輯判斷式),目的是為了標示與驗證程式開發者預期的結果-當程式執行到斷言的位置時,對應的斷言應該為真。若斷言不會真時,程式會中止執行,並出現錯誤訊息。
Programmers can use assertions to help specify programs and to reason about program correctness. For example, a precondition—an assertion placed at the beginning of a section of code—determines the set of states under which the programmer expects the code to execute. A postcondition—placed at the end—describes the expected state at the end of execution.
程式設計者可以用斷言來標示程式,提供程式正確性的相關資訊。例如在一段程式前加入斷言(先驗條件),說明這段程式執行前預期的狀態。或在一段程式後加入斷言(後驗條件),說明這段程式執行後預期的結果。
In languages such as Eiffel, assertions form part of the design process; other languages, such as C and Java, use them only to check assumptions at runtime. In both cases, they can be checked for validity at runtime but can usually also be suppressed.
在開發Eiffel語言的程式時,斷言是設計過程中的一部份。像C語言或Java等程式語言,主要在執行期檢查斷言是否正確,也可以用靜態斷言的方式,在編譯期檢查斷言。不論是哪一種情形,都可以檢查斷言的有效性,也可以關閉斷言檢查的機能。
1、编程断言:
assert()
是一个诊断宏,用于动态辨识程序的逻辑错误条件。其原型是:1 #include "assert.h" 2 void assert( int expression );
如果宏的参数求值结果为非零值,则不做任何操作(no action);如果是零值,用宽字符打印诊断消息,然后调用abort()
。诊断消息包括:
stdlib.h
中声明的宏__FILE__
的值)stdlib.h
中声明的宏__LINE__
的值)__func__
的值),这是C99新增的特性诊断信息的显示目标依赖于被调用程序的类型。如果是控制台程序,诊断信息显示在stderr设备;如果是基于窗口的程序,assert()
产生一个Windows MessageBox来显示诊断信息。
使用assert的缺点是,频繁的调用会极大的影响程序的性能,增加额外的开销。
在调试结束后,可以通过在包含#include 的语句之前插入 #define NDEBUG 来禁用assert调用,示例代码如下:
1 #include 2 #define NDEBUG 3 #include
Assertion (software development) -- 断言
标签:des style blog http color io os 使用 java
原文地址:http://www.cnblogs.com/xymqx/p/3990427.html