我如何做这样some_function({1,1,1,1})? [英] How do I do something like this some_function({1,1,1,1})?

查看:117
本文介绍了我如何做这样some_function({1,1,1,1})?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个类似这样的函数: int func(int * a),它接受一个数组作为参数。

Lets say I have a function with prototype like this: int func(int * a), and it accepts an array as an argument.

如果没有编译器显示错误,我该怎么做:func({1,1,1,1})

How do I do this without the compiler showing errors everywhere: func({1,1,1,1})

推荐答案

所有你需要的是(int []) cast:

All you need is an (int[]) cast:

#include <iostream>

static void f (int* a) {
  while (*a) std::cout << *a++ << "\n" ;
  }

int main() {
  f ((int[]){1,2,3,4,0}) ;
  }

此代码输出

1
2
3
4


b $ b

它在C中也有效 - 请参见此意见链接

已更新添加:我发布了有关这个结构的合法性,以及 Mat的回答值得阅读,如果你对这种事情感兴趣。简单来说,它似乎只在C99有效,但一些编译器允许它作为所有C / C ++变体中的扩展。

Updated to add: I posted a new question about the legality of this construct, and Mat's answer is worth reading if you're interested in that kind of thing. Briefly, it seems that it is valid only in C99, but that some compilers allow it as an extension in all C/C++ variants.

这篇关于我如何做这样some_function({1,1,1,1})?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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