简体   繁体   English

我如何在c中解释(断言)?

[英]How do I interpret (assert) here in c?

void (assert)(int e)
{
    assert(e);
}

How does it work here? 它在这里如何运作?

void (assert)(int e) is equivalent to void assert(int) void (assert)(int e)等同于void assert(int)

Why would you need it? 你为什么需要它?

Consider the following example 考虑下面的例子

#include<stdio.h>
void foo(int a)
{
printf("%d", a);
}
#define foo(a) {/*I do nothing*/}

int main()
{
  foo(5); // won't call `foo`
}

How would you make sure when you call foo , its the function that is called and not the macro-definition substituted at the place of call? 您如何确定调用foo ,即调用的函数而不是在调用位置替换的宏定义?

The solution is to put an extra parenthesis like (foo)(5) 解决方案是在括号中加上(foo)(5)

Similarly assert is already known to be a macro. 类似地, assert已知是一个宏。 That's the reason I can think of. 这就是我能想到的原因。

Since assert already is defined as a function-style macro, without the parentheses it would have been expanded both in the function header and in the body. 由于assert已经被定义为函数式宏,没有它会无论是在功能头部和身体被扩大了括号。

For example: 例如:

#define twice(x) ((x)+(x))
void twice(int i)
{
  return twice(i);
}

Will expand to the following, which clearly is not legal 将扩展到以下内容,这显然是不合法的

void ((int i)+(int i))
{
  return ((i)+(i));
}

On the other hand: 另一方面:

#define twice(x) ((x)+(x))
void (twice)(int i)
{
  return twice(i);
}

Will expand to: 将扩展为:

void (twice)(int i)
{
  return ((i)+(i));
}

The extra parentheses around the function name is simply ignored by the compiler. 编译器将忽略函数名称周围的多余括号。

This is a common trick often used in the source of the standard library, on in other contexts where there might be functions and macros with the same name. 这是在标准库的源代码中经常使用的常见技巧,在其他情况下,其中可能存在具有相同名称的函数和宏。

It's legal syntax, just writing it with extra parentheses. 这是合法的语法,只是用额外的括号写出来。 The reason you'd do that is because assert() is often defined as a macro; 之所以这样做,是因为assert()通常被定义为宏。 so the above function exists to make assert() be a real function, probably so you can set a breakpoint in it. 因此上面的函数可以使assert()成为一个实函数,因此您可以在其中设置一个断点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM