C中的复合语句表达式

发布于 2025-01-21 11:49:03 字数 243 浏览 2 评论 0原文

以下代码不起作用。

int i = {(void) 999; 100;}; 

添加括号将起作用。为什么?

int i = ({(void) 999; 100;}); 

还有另一种方法可以进行这种分配:

int i = ((void) 999, 100); 

是什么使它们与众不同?

Below code is not working.

int i = {(void) 999; 100;}; 

Adding parentheses will work. WHY?

int i = ({(void) 999; 100;}); 

There is another way to do this type of assignment:

int i = ((void) 999, 100); 

What make them different?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

皇甫轩 2025-01-28 11:49:03

在此声明中,

int i = {(void) 999; 100;}; 

括号内有两个语句

(void) 999; 

100;

作为初始化器。

这在句法上无效。要使用括号中包含的列表初始化标量对象,您可以仅使用一个分配表达式,也不使用两种语句。

这种结构

int i = ({(void) 999; 100;});

也是无效的C结构。但是,包含在括号中的复合语句可能以GNU C的表达方式出现。它是其自己的语言扩展。表达式的值为100。这是由值100初始化的变量I。

此声明

int i = ((void) 999, 100); 

是唯一有效的C构造。在括号内使用了逗号操作员。表达式的价值是表达式最多的正确操作数为100。

实际上,最后一个声明等于

int i = 100;

编译器,应发出警告,即表达式(void)999没有效果。

In this declaration

int i = {(void) 999; 100;}; 

there are used two statements inside the braces

(void) 999; 

and

100;

as initializers.

This is syntactically invalid. To initialize a scalar object using a list enclosed in braces you may use only one assignment expression and neither statements.

This construction

int i = ({(void) 999; 100;});

is also an invalid C construction. However a compound statement enclosed in parentheses may appear as an expression in GNU C. It is its own language extension. The value of the expression is 100. That is the variable i is initialized by the value 100.

This declaration

int i = ((void) 999, 100); 

is the only valid C construction. Within the parentheses there is used the comma operator. The value of the expression is the right most operand of the expression that is 100.

In fact the last declaration is equivalent to

int i = 100;

The compiler should issue a warning that the expression ( void )999 has no effect.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文