简体   繁体   English

C中的圆括号和大括号代码块

[英]Round and curly bracket block of code in C

Can anyone explain what this macro evaluates to:谁能解释这个宏的计算结果:

#define memcpy(dest,src,n) ({ \
void * _res = dest; \
__asm__ ("cld;rep;movsb" \
    ::"D" ((long)(_res)),"S" ((long)(src)),"c" ((long) (n)) \
    :"di","si","cx"); \
_res; \
})

This is taken from the first version of Linux kernel, but I am wondering what does a block of code surrounded by this ({ }) represent and where would it be used?这取自 Linux kernel 的第一个版本,但我想知道被这个({ })包围的代码块代表什么以及它会在哪里使用?

A compound statement in parentheses is a GCC extension called a statement expression.括号中的复合语句是 GCC 扩展,称为语句表达式。 It allows you to include declarations, for loops etc where an expression is expected.它允许您在需要表达式的地方包含声明、for 循环等。 The last thing in the compound statement should be an expression followed by a semicolon which serves as the value of the entire construct.复合语句中的最后一件事应该是一个表达式,后跟一个分号,作为整个构造的值。

The clang compiler also has support for them. clang 编译器也支持它们。

They are mainly just a convenience to remove the need to write lots of small functions that are only used once but are also used to prevent problems with macros when a term appears more than once;它们主要是为了方便,无需编写大量只使用一次的小函数,但也可用于防止在一个术语出现多次时出现宏问题; for example:例如:

#define maxint(a,b) \
       ({int _a = (a), _b = (b); _a > _b ? _a : _b; })

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

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