为什么我不能将常量数组作为参数传递? [英] Why can't I pass constant arrays as arguments?

查看:43
本文介绍了为什么我不能将常量数组作为参数传递?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 C 中,为什么我不能这样做:

In C, why can't I do this:

arrayfn({1.0, 2.0, 3.0});

if arrayfn 是一个接受 double[]double* 类型参数的函数.尝试这个会给我一个语法错误.

if arrayfn is some function that takes in one parameter of type double[] or double*, whichever. Trying this gives me a syntax error.

有没有一种方法可以让我在 C 中实现这样的目标——生成并立即传递一个在编译时已知的数组——从而避免花费一行代码预先声明和填充它?

Is there a way that I could achieve something in C like this - generating and immediately passing an array known at compile time - that avoids having to spend a line of code pre-declaring and filling it?

推荐答案

简短回答:您需要使用 复合文字.类似的东西

Short answer: You need to make use of a compound literal. Something like

 arrayfn( (double[]) {1.0, 2.0, 3.0} );

应该完成这项工作.

一些解释

说到这部分,为什么 arrayfn({1.0, 2.0, 3.0}); 不起作用,因为如果没有复合文字的语法,{1.0, 2.0, 3.0} 是一个花括号括起来的初始化列表.它不表示可以用作函数参数的对象".它们不是常量数组",正如您所想的那样.

Coming to the part, why arrayfn({1.0, 2.0, 3.0}); did not work, because, without the syntax for compound literals, {1.0, 2.0, 3.0} is a brace enclosed initializer list. It does not denote an "object" which can be used as function argument. They are not "constant arrays", as you may have thought.

要添加更多信息,请引用 C11,章节 §6.5.2.5,复合文字

To add some more info, quoting C11, chapter §6.5.2.5, Compound literals

后缀表达式由带括号的类型名称和花括号括起来的类型名称组成初始值设定项列表是复合文字.它提供了一个未命名的对象,其值由初始化列表给出.

A postfix expression that consists of a parenthesized type name followed by a brace-enclosed list of initializers is a compound literal. It provides an unnamed object whose value is given by the initializer list.

这篇关于为什么我不能将常量数组作为参数传递?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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