如何在不使用变量 C/C++ 的情况下将常量数组文字传递给采用指针的函数?

2022-11-12C/C++开发问题
2

本文介绍了如何在不使用变量 C/C++ 的情况下将常量数组文字传递给采用指针的函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

如果我有一个看起来像这样的原型:

If I have a prototype that looks like this:

function(float,float,float,float)

我可以传递这样的值:

function(1,2,3,4);

如果我的原型是这样的:

So if my prototype is this:

function(float*);

有什么办法可以实现这样的目标吗?

Is there any way I can achieve something like this?

function( {1,2,3,4} );

只是在寻找一种懒惰的方法来做到这一点而不创建临时变量,但我似乎无法确定语法.

Just looking for a lazy way to do this without creating a temporary variable, but I can't seem to nail the syntax.

推荐答案

您可以在 C99(但不是 ANSI C (C90) 或 C++ 的任何当前变体)中使用 复合文字.有关详细信息,请参阅 C99 标准的第 6.5.2.5 节.举个例子:

You can do it in C99 (but not ANSI C (C90) or any current variant of C++) with compound literals. See section 6.5.2.5 of the C99 standard for the gory details. Here's an example:

// f is a static array of at least 4 floats
void foo(float f[static 4])
{
   ...
}

int main(void)
{
    foo((float[4]){1.0f, 2.0f, 3.0f, 4.0f});  // OK
    foo((float[5]){1.0f, 2.0f, 3.0f, 4.0f, 5.0f});  // also OK, fifth element is ignored
    foo((float[3]){1.0f, 2.0f, 3.0f});  // error, although the GCC doesn't complain
    return 0;
}

GCC 也将此作为 C90 的扩展提供.如果您使用 -std=gnu90(默认值)、-std=c99-std=gnu99 编译,它将编译;如果使用 -std=c90 编译,则不会.

GCC also provides this as an extension to C90. If you compile with -std=gnu90 (the default), -std=c99, or -std=gnu99, it will compile; if you compile with -std=c90, it will not.

这篇关于如何在不使用变量 C/C++ 的情况下将常量数组文字传递给采用指针的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

无法访问 C++ std::set 中对象的非常量成员函数
Unable to access non-const member functions of objects in C++ std::set(无法访问 C++ std::set 中对象的非常量成员函数)...
2024-08-14 C/C++开发问题
17

从 lambda 构造 std::function 参数
Constructing std::function argument from lambda(从 lambda 构造 std::function 参数)...
2024-08-14 C/C++开发问题
25

STL BigInt 类实现
STL BigInt class implementation(STL BigInt 类实现)...
2024-08-14 C/C++开发问题
3

使用 std::atomic 和 std::condition_variable 同步不可靠
Sync is unreliable using std::atomic and std::condition_variable(使用 std::atomic 和 std::condition_variable 同步不可靠)...
2024-08-14 C/C++开发问题
17

在 STL 中将列表元素移动到末尾
Move list element to the end in STL(在 STL 中将列表元素移动到末尾)...
2024-08-14 C/C++开发问题
9

为什么禁止对存储在 STL 容器中的类重载 operator&()?
Why is overloading operatoramp;() prohibited for classes stored in STL containers?(为什么禁止对存储在 STL 容器中的类重载 operatoramp;()?)...
2024-08-14 C/C++开发问题
6