函数参数上的分号

Semicolon on a function parameters

本文关键字:参数 函数      更新时间:2023-10-16
matrix_* matrix_insert_values(int n; double a[][n], int m, int n)
{
    matrix_* x = matrix_new(m, n);
    for (int i = 0; i < m; i++)
        for (int j = 0; j < n; j++)
            x->v[i][j] = a[i][j];
    return x;
}

我的测试矩阵示例

double in[][3] = {
    { 12, -51,   4},
    {  6, 167, -68},
    { -4,  24, -41},
    { -1, 1, 0},
    { 2, 0, 3},
};

我有点迷路了,我不知道int n;在我的参数声明中是什么,它在C上工作,但c++不允许这种实现。我想了解这是如何工作的,因为我要把这段代码迁移到c++。

这是C99 GNU扩展(GCC文档)中很少使用的特性,用于前向声明VLA声明器中使用的参数。

matrix_* matrix_insert_values(int n; double a[][n], int m, int n);

你看到int n出现了两次吗?第一个int n;只是实际的int n的前向声明,它在最后。它必须出现在double a[][n]之前,因为a的声明中使用了n。如果你愿意重新排列参数,你可以把n放在a之前,这样你就不需要这个特性了

matrix_* matrix_insert_values_rearranged(int m, int n, double a[][n]);

c++兼容性注意事项

要清楚,GNU扩展只是函数参数的前向声明。下面的原型是标准C:

// standard C, but invalid C++
matrix_* matrix_insert_values_2(int m, int n, double a[][n]);

不能从c++中调用这个函数,因为这段代码使用了可变长度数组,在c++中是不支持的。为了能够从c++中调用它,您必须重写该函数。

如果你总是这样在C中调用它(即n和m在编译时固定),那么在c++中你可以这样做:

template <int N, int M>
void matrix_insert_values(const double (&a)[M][N]);
int main() {
  double in[5][3] = {
    { 12, -51,   4},
    {  6, 167, -68},
    { -4,  24, -41},
    { -1, 1, 0},
    { 2, 0, 3},
  };
  matrix_insert_values(in);
};

以N和M作为模板参数,这些参数在编译时从传递给函数的输入中自动推导出来。