江山演唱的原唱歌曲:ASSERT函数

来源:百度文库 编辑:偶看新闻 时间:2024/04/26 18:56:21
ASSERT()是一个调试程序时经常使用的宏,在程序运行时它计算括号内的表达式,如果表达式为FALSE  (0),  程序将报告错误,并终止执行。如果表达式不为0,则继续执行后面的语句。这个宏通常原来判断程序中是否出现了明显非法的数据,如果出现了终止程序以免导致严重后果,同时也便于查找错误。  

ASSERT只有在Debug版本中才有效,如果编译为Release版本则被忽略。  
---------------------------------------------------------------  

ASSERT宏定义如下  

#define  ASSERT(f)  \  
do  \  
{  \  
      if  (!(f)  &&  AfxAssertFailedLine(THIS_FILE,  __LINE__))  \  
              AfxDebugBreak();  \  
}  while  (0)  \  

ASSERT(逻辑表达式)  

如果括号中的逻辑表达式值为假的话,会弹出调试命令窗口,提示具体在哪个文件的哪一行发生了断言错误!  
---------------------------------------------------------------  

ASSERT  
Evaluates  an  expression,  and  displays  a  diagnostic  message  if  the  expression  is  FALSE.  Ignored  in  retail  builds.  

Syntax  

ASSERT(  
      cond  
);  

Parameters  

cond  

Expression  to  evaluate.  

Remarks  

In  debug  builds,  if  the  expression  is  FALSE,  this  macro  displays  a  message  box  with  the  text  of  the  expression,  the  name  of  the  source  file,  and  the  line  number.  The  user  can  ignore  the  assertion,  enter  the  debugger,  or  quit  the  application.  

Example  

ASSERT(rtStartTime  <=  rtEndTime);  


---------------------------------------------------------------  

断言(ASSERT)的使用,方法很简单。为什么要用,初学者可能比较迷惑。  
契约式编程讲的比较清楚,建议可以先看看这类书。  
一个函数由前置条件、后置条件和不变式组成。在VC中,我们可以通过断言来保证这三个条件。可以大大提高了软件的质量。  
---------------------------------------------------------------  

如果ASSERT()中的条件不成立(比如  ASSERT(0)  ;    ),会弹出一个比较吓人的对话框。  

点击重试,可以到达  ASSERT  断言不成立的那一行,  

此时可以在watch窗口查看变量值,找出出错的原因。  

如果程序能够继续运行,可以按F5继续调试。