assert.h中的C ++ assert实现

问题描述 投票:12回答:4
00001 /* assert.h
00002    Copyright (C) 2001, 2003 Free Software Foundation, Inc.
00003    Written by Stephane Carrez ([email protected])       
00004 
00005 This file is free software; you can redistribute it and/or modify it
00006 under the terms of the GNU General Public License as published by the
00007 Free Software Foundation; either version 2, or (at your option) any
00008 later version.
00009 
00010 In addition to the permissions in the GNU General Public License, the
00011 Free Software Foundation gives you unlimited permission to link the
00012 compiled version of this file with other programs, and to distribute
00013 those programs without any restriction coming from the use of this
00014 file.  (The General Public License restrictions do apply in other
00015 respects; for example, they cover modification of the file, and
00016 distribution when not linked into another program.)
00017 
00018 This file is distributed in the hope that it will be useful, but
00019 WITHOUT ANY WARRANTY; without even the implied warranty of
00020 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
00021 General Public License for more details.
00022 
00023 You should have received a copy of the GNU General Public License
00024 along with this program; see the file COPYING.  If not, write to
00025 the Free Software Foundation, 59 Temple Place - Suite 330,
00026 Boston, MA 02111-1307, USA.  */
00027 
00028 #ifndef _ASSERT_H
00029 #define _ASSERT_H
00030 
00031 #ifdef NDEBUG
00032 # define assert(EX)
00033 #else
00034 # define assert(EX) (void)((EX) || (__assert (#EX, __FILE__, __LINE__),0))
00035 #endif
00036 
00037 #ifdef __cplusplus
00038 extern "C" {
00039 #endif
00040 
00041 extern void __assert (const char *msg, const char *file, int line);
00042 
00043 #ifdef __cplusplus
00044 };
00045 #endif
00046 #endif

问题是:第34行的“(void)”是什么,__ assert是什么?

c++ implementation assert
4个回答
14
投票

查看此行:

extern void __assert (const char *msg, const char *file, int line);

__assert是将断言消息,文件名和行号作为参数的函数。基本上,这是一种输出错误消息并在断言失败时终止程序的方法。

然后查看上面的宏定义:

#define assert(EX) (void)((EX) || (__assert (#EX, __FILE__, __LINE__),0))

[它定义了assert(EX)宏,因此,它首先检查EX表达式,并且(由于C ++ ||运算符的短路操作))只有在失败时才调用__assert函数并传递失败的断言异常作为字符串,以及assert()方法调用在源文件中的确切位置。通过这种预处理器技巧,当您在程序中键入以下内容时,断言库可以实现这一点]

assert(a == 0);

并且您的断言在程序运行期间失败,您将获得详细的信息

Assertion failed: a == 0 at program.c, line 23

错误消息,可帮助您确定断言在代码中失败的确切位置。

(void)部分仅用于确保编译器不会对(EX) || 0表达式的未使用结果发出警告,请参见其他答案,这些人都很好地解释了。

剩余的预处理器定义NDEBUG用于在所有编译时都转为声明生成,您生成的可执行文件将更小,更快。


7
投票

__assert是实现的一部分;在这种情况下,库中的一个函数将在断言失败的情况下被调用。 (void)只是关闭有关||运算符未使用结果的编译器警告。


1
投票

它禁止有关未使用的值或变量的编译器警告。


1
投票

几乎...

© www.soinside.com 2019 - 2024. All rights reserved.