`用C;对`({})的更多信息? [英] More information on `({});` in C?

查看:93
本文介绍了`用C;对`({})的更多信息?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我注意到,有时,C宏被写成这样的:

I've noticed that sometimes, C macros are written as something like this:

#define foo(bar) ({ ++bar; })

一些实验后,我发现:

After some experimentation, I've found that:


  1. ({}); 将编译,但也无可奈何。 (正如预期的那样。)

  2. 离开; 关闭将导致语法错误。这样做的副作用是确保富()看起来像在code函数。 (虽然,如果你离开分号了,错误不是诊断问题非常有用!)

  3. 收益率({}); 抱怨没有被忽视,一个空值就像如果我曾试图用一个void函数

  1. ({}); will compile, but do nothing. (As expected.)
  2. Leaving the ; off will cause a syntax error. A side effect of this is ensuring that foo() looks like a function in your code. (Although, if you leave the semicolon off, the error isn't very useful for diagnosing the problem!)
  3. return ({}); complains about a void value not being ignored, just like if I had tried to use a void function.

这是只是为了开发一个分号添加到自己的宏,还是有其他目的?我尝试过谷歌,但它与标点符号悲惨的失败了。是否有此名字?

Is this just to make developers add a semicolon to their macros, or does it have another purpose? I've tried Google, but it fails miserably with punctuation. Is there a name for this?

推荐答案

这是一个GNU扩展名为的语句前pressions 的。

This is a GNU extension called statement expressions.

在声明宏在标准C,你经常会看到做...而(0)用于类似用途循环(即创建一个块范围内)。声明前pression优于循环黑客,因为它可以返回一个值。如果你想要做标准-C类似的东西,你必须定义一个附加功能,失去词法范围的便利性。

When declaring macros in standard-C, you often see do...while(0) loops used for similar purposes (ie creating a block scope). A statement expression is superior to the loop hack because it can return a value. If you want to do something similar in standard-C, you'd have to define an additional function and lose the convenience of lexical scoping.

这篇关于`用C;对`({})的更多信息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆