assert()
是一个诊断宏,用于动态辨识程序的逻辑错误条件。其原型是:void assert(int expression);
如果宏的参数求值结果为非零值,则不做任何操作(no action);如果是零值,用宽字符打印诊断消息,然后调用abort()
。
异常时打印的诊断消息包括:
- 源文件名字(在
stdlib.h
中声明的宏__FILE__
的值) - 所在的源文件的行号(在
stdlib.h
中声明的宏__LINE__
的值) - 所在的函数名(在stdlib.h中声明的宏
__func__
的值),这是C99新增的特性 - 求值结果为0的表达式
诊断信息的显示目标依赖于被调用程序的类型。如果是控制台程序,诊断信息显示在stderr设备;如果是基于窗口的程序,assert()
产生一个Windows MessageBox来显示诊断信息。[ 控制台程序:
就是没有独立窗口的程序。一般在命令行运行,输入输出通过标准IO进行,不象界面程序可以通过鼠标点击进行操作。一般后台运行的程序可作为控制台应用程序。
http://en.wikipedia.org/wiki/Console
http://en.wikipedia.org/wiki/Console_application
]
程序可以屏蔽掉所有的assert()
而无需修改源代码。这只需要在命令行调用C语言的编译器时添加宏定义的命令行选项,定义DNDEBUG
宏;也可以在源程序程序引入<assert.h>
之前就使用#define NDEBUG
来定义宏。被屏蔽的assert()
甚至不对传递给它的参数表达式求值,因此使用assert()
时其参数表达式不能有副作用(side-effects)。
A console application is a computer program designed to be used via a text-only computer interface, such as atext terminal, thecommand line interface of someoperating systems (Unix,DOS, etc.) or the text-based interface included with mostGraphical User Interface (GUI) operating systems, such as theWin32 console inMicrosoft Windows, theTerminal inMac OS X, andxterm in Unix. A user typically interacts with a console application using only akeyboard anddisplay screen, as opposed to GUI applications, which normally require the use of a mouse or otherpointing device. Many console applications such ascommand line interpreters arecommand line tools, but numeroustext-based user interface (TUI) programs also exist.
As the speed and ease-of-use of GUI applications have improved over time, the use of console applications has greatly diminished, but not disappeared. Some users simply prefer console based applications, while some organizations still rely on existing console applications to handle key data processing tasks.
The generation of console applications is kept as a feature of modernprogramming environments such asVisual Studio and the.NET Framework on Microsoft Windows because it greatly simplifies the learning process of a new programming language by removing the complexity of a graphical user interface (see an example in theC# article).
For data processing tasks and computer administration, these programming environments represent the next level of operating system or data processing control afterscripting. If an application is only going to be run by the programmer himself and/or a few colleagues, there may be no need for a pretty graphical user interface, leaving the application leaner, faster and easier to maintain.