为什么我不能通恒数组作为参数? [英] Why can't I pass constant arrays as arguments?

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

问题描述

在C,我为什么不能做到这一点:

In C, why can't I do this:

arrayfn({1.0, 2.0, 3.0});

如果 arrayfn 一些函数,接受类型双[] 双* 为准。想这给了我一个语法错误。

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

有没有办法,我可以实现用C像这样的一种方式 - 发电,并立即通过在编译时已知阵列 - 这避免了花线code pre-声明和填充呢?

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

一个后缀前pression,由带括号的类型名称,后跟一个括号封闭的
  初始化列表是文字的化合物。它提供了一个未命名的对象,其值由初始化列表给出。

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天全站免登陆