是否可以在定义点下标数组文字?

Is it possible to subscript an array literal at the point of definition?

我想在定义点下标数组文字,因为在初始访问后我不需要数组:

int func(int index) {
   return {1, 2, 3, 4, 5}[index];
}

注意:数组元素比这个例子更复杂。我也省略了边界检查。我只是好奇 C 语法是否允许这种 construct/shortcut.

编译以上代码结果:

error: syntax error before `{' token

Python 等同于我在 C:

中试图实现的目标
def func(index):
    return [1,2,3,4,5][index]

你可以使用所谓的复合文字:

#include <stdio.h>
 
int main(void) {
    printf("%d\n", 
       (int[]){1,2,3,4,5}[2]);
    return 0;
}

参考C标准草案部分6.5.2.5 Compound Literals

我不太明白这一点,但你可以用 C:

中的复合文字来做到这一点
int func(int index) {
   return (int[]){1, 2, 3, 4, 5}[index];
}

更好、更易读的版本:

int func(int index) {
   const int[] local = {1, 2, 3, 4, 5};
   return local[index];
}

两种情况下生成的机器码都是一样的。