c - 这种分配风格是否定义明确?

标签 c

我在第 6 行中给出了一个示例来说明我指的是哪种分配风格。

  1 #include<stdio.h>
  2 
  3 int main(int argc,char *argv[])
  4 {
  5         int a,b,c;
  6         c = ({ a=5; b = a+1;});
  7         printf("%d\n%d\n%d\n",a,b,c);
  8         return 0;
  9 }

我不确定 {} 是什么。它不是数组 int arr[]={1,2,3} 中使用的初始化列表。


更新: 也许使用这种方法我可以在函数中定义一个函数或者在 gcc 中定义一个错误(版本 4.7.2(Ubuntu/Linaro 4.7.2-2ubuntu1))

  1 #include<stdio.h>
  2 #include<math.h>
  3 int main(int argc,char *argv[])
  4 {
  5         int a,b;
  6         b = ({int cos(i){return 0;};a = 0;cos(a);});
  7         printf("%d\n%d\n",a,b);
  8         b = cos(0);
  9         printf("%d\n%d\n",a,b);
 10         return 0;
 11 }

输出:

0
0
0
1 

最佳答案

({ a=5; b = a+1;})

是一个 GNU 扩展,一个 expression statement .这不是标准的 C。

block 中的语句被执行, block 中最后一个表达式的值为该表达式语句的值。

所以

c = ({ a=5; b = a+1;});

a 设置为 5,然后将 b 设置为 a+1 (6),将 c 设置为值(value)。


关于更新,

b = ({int cos(i){return 0;};a = 0;cos(a);});

另外使用另一个 GNU 扩展,nested functions .在表达式语句的复合语句中,定义了一个嵌套函数 cos,隐藏了 math.h 中声明的名称 cos,因此cos(a) 即复合语句中的最后一个表达式调用嵌套的局部定义。

第8行,嵌套函数当然不在范围内,所以

b = cos(0);

调用 math.h 中的一个。

关于c - 这种分配风格是否定义明确?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15987184/

相关文章:

c - C中的只读字符串

iphone - 在 Objective-C block 中调用 C 函数(链接器错误)

c - 双重释放或腐败(fasttop)

C语言: why c language has 'class' ?

c - 定义字符串数组

c - 如何将二维数组返回到 main()

c - 如何使用 pthread 管理 c 中的多个线程?

c - 将代码从 MATLAB 移植到 C(OpenCV)

c - 声明的变量堆栈

c++ - hello world 在 gcc 5.3.0/bin/ld : invalid option -- 'p' 上失败