1ms Faster
Home
  • Program

    • Lean in C++
  • Perfromance Engineering

    • [>>>>>]
  • Reading Note

    • [>>>>>]
  • ComputeArch

    • [_]
  • Compiler

    • [_]
  • System

    • [_]
Authoring
  • Categories
  • Tags
GitHub (opens new window)

Quincy Jet

We are.
Home
  • Program

    • Lean in C++
  • Perfromance Engineering

    • [>>>>>]
  • Reading Note

    • [>>>>>]
  • ComputeArch

    • [_]
  • Compiler

    • [_]
  • System

    • [_]
Authoring
  • Categories
  • Tags
GitHub (opens new window)
  • Lean in c++

    • Lean in C++
    • Phase_0:Glimpse

      • C++ Glimpse
      • type cast
      • typedef
      • class vs. typename
      • const
      • extern
      • pointer
      • static
      • volatile
      • inline
      • assert
        • 2.assert与正常错误处理
      • void
      • __global__
  • Performance Engineering

  • Misc

  • Reading Notes

  • Wiki
  • Lean in c++
  • Phase_0:Glimpse
Quincy Jet
2021-08-05
Content

assert

断言,是宏,而非函数。

assert 宏的原型定义在 <assert.h>(C)(C++)中。其作用是如果它的条件返回错误,则终止程序执行。

void assert(int expression);
1

可以通过定义 NDEBUG 来关闭 assert,但是需要在源代码的开头,include <assert.h> 之前。

#include <stdio.h> 
#include <assert.h> 

int main() 
{ 
    int x = 7; 

    /*  Some big code in between and let's say x  
    is accidentally changed to 9  */
    x = 9; 

    // Programmer assumes x to be 7 in rest of the code 
    assert(x==7); 

    /* Rest of the code */

    return 0; 
} 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

输出:

assert: assert.c:13: main: Assertion 'x==7' failed.
1

可以看到输出会把源码文件,行号错误位置,提示出来!

# 2.assert与正常错误处理

  • assert主要用于检查逻辑上不可能的情况。

例如,它们可用于检查代码在开始运行之前所期望的状态,或者在运行完成后检查状态。与正常的错误处理不同,断言通常在运行时被禁用。

  • 忽略断言,在代码开头加上:
#define NDEBUG          // 加上这行,则 assert 不可用
1
#C++
Last updated: 2023/03/11, 03:13:10
inline
void

← inline void→

Copyright © 2017-2023 Quincy Jet | MIT License
  • Auto
  • Light
  • Dark
  • Read