在什么版本的C是用于返回有效的值在括号内的块? [英] In what versions of C is a block inside parenthesis used to return a value valid?

查看:109
本文介绍了在什么版本的C是用于返回有效的值在括号内的块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我做的:

  INT J =({INT X = 7; X + 3;});

在i686的-苹果darwin10-GCC-4.2.1(GCC)4.2.1(苹果公司建立5646)的gcc它编译就好了。有问题的块({INT X = 7; X + 3;})返回最后一个语句块的价值的价值。如果去掉括号不编译。我可以期待这在大多数C编译器的工作?

此外,究竟是什么构造的名字吗?我有很多麻烦寻找它,因为搜索引擎不索引() {} 和C是一个可怕的搜索词。我也一直没能找到关于它的任何我的书什么,可能是因为我不知道要寻找什么。


解决方案

  

如果您删除括号它不会编译。


如果没有括号,编译器会将此视为一个集合初始化块,当它看到 INT 关键字将失败。你不能在初始化块关键字。


  

6.7.8初始化


  
  

11 作为一个标量初始化应该是单个前pression,可选大括号括起来。该
  对象的初始值是前pression(变换后)的;相同类型
  约束和转换为简单任务应用,同时标量的类型
  是其声明的类型的无保留意见的版本。


  
  

6.2.5类型


  
  

21 运算类型和指针类型统称标量类型。数组和
  结构类型统称为聚合类型。




  

我可以期待这在大多数C编译器的工作?


没有。看起来像一个非标准的GNU扩展。


  

此外,究竟是什么构造的名字吗?


我不知道是否有任何。其实,这是类似于宏通常做的。

If I do:

int j = ({int x = 7; x+3;});

In i686-apple-darwin10-gcc-4.2.1 (GCC) 4.2.1 (Apple Inc. build 5646) gcc it compiles just fine. The block in question ({int x = 7; x+3;}) returns the value of the last statement as the value of the block. If you remove the parenthesis it doesn't compile. Can I expect this to work in most C compilers?

Additionally, what is the name for this construct? I have had a lot of trouble searching for it because search engines don't index () or {} and C is a terrible search term. I also haven't been able to find anything about it in any of my books, probably because I don't know what to look for.

解决方案

If you remove the parenthesis it doesn't compile.

Without the parentheses, the compiler will treat this as an aggregate initialization block and will fail when it sees the int keyword. You cannot have keywords in initializer blocks.

6.7.8 Initialization

11 The initializer for a scalar shall be a single expression, optionally enclosed in braces. The initial value of the object is that of the expression (after conversion); the same type constraints and conversions as for simple assignment apply, taking the type of the scalar to be the unqualified version of its declared type.

6.2.5 Types

21 Arithmetic types and pointer types are collectively called scalar types. Array and structure types are collectively called aggregate types.


Can I expect this to work in most c compilers?

No. Looks like a non-standard GNU extension.

Additionally, what is the name for this construct?

I wonder if there is any. Actually, this is similar to what macros typically do.

这篇关于在什么版本的C是用于返回有效的值在括号内的块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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