在浏览一些源代码时,我遇到了这样的函数:
void someFunction(char someArray[static 100])
{
// do something cool here
}
Run Code Online (Sandbox Code Playgroud)
通过一些实验,似乎其他限定符也可能出现在那里:
void someFunction(char someArray[const])
{
// do something cool here
}
Run Code Online (Sandbox Code Playgroud)
似乎只有[
]
在将数组声明为函数的参数时才允许使用限定符.这些怎么办?为什么功能参数不同?
在函数中使用变长数组作为参数时
int sum(int n, int a[n]);
Run Code Online (Sandbox Code Playgroud)
很容易理解第一个参数(n
)指定第二个参数(a
)的长度.但遇到另一个用于VLA的原型作为参数
int sum(int n, int a[*]);
Run Code Online (Sandbox Code Playgroud)
真的很难理解为什么*
用而不是在n
里面[]
?
我有以下C代码示例:
int f(const int farg[const 5])
{
}
Run Code Online (Sandbox Code Playgroud)
数组大小的附加const有什么作用?当我省略const时有什么区别?
这是C++ Primer第5版的练习,其中包括:
练习6.24:解释以下功能的行为.如果代码中存在问题,请说明它们是什么以及如何解决它们.
void print(const int ia[10])
{
for (size_t i = 0; i != 10; ++i)
cout << ia[i] << endl;
}
Run Code Online (Sandbox Code Playgroud)
我在代码中找不到任何问题.这个练习有什么意义?
C99 在函数参数中添加了static(仅在函数定义中有意义,而不是声明):
void func( int a[static 10] )
{
if ( a == NULL )
{ /* this branch can be optimized out */ }
printf("%d", a[-1]); /* causes UB */
}
Run Code Online (Sandbox Code Playgroud)
但是,它的含义在C11 6.7.6.3/7中定义为语义,而不是约束,这意味着如果函数调用不正确,编译器不应发出诊断.事实上,编译器不能中止编译,除非它能证明UB是在所有分支中引起的.例如:
int main()
{
func(NULL); // UB
int b[9];
func(b); // UB
}
Run Code Online (Sandbox Code Playgroud)
为什么标准没有将此作为约束(因此需要诊断)?
次要问题:为什么static
在原型(6.7.6.3/13)中被忽略,而不是作为功能签名的一部分?允许原型包含它但功能体不包含它似乎有误导性,反之亦然.
我正在探索如何基于函数签名在C99中简单循环的不同实现自动矢量化。
这是我的代码:
/* #define PRAGMA_SIMD _Pragma("simd") */
#define PRAGMA_SIMD
#ifdef __INTEL_COMPILER
#define ASSUME_ALIGNED(a) __assume_aligned(a,64)
#else
#define ASSUME_ALIGNED(a)
#endif
#ifndef ARRAY_RESTRICT
#define ARRAY_RESTRICT
#endif
void foo1(double * restrict a, const double * restrict b, const double * restrict c)
{
ASSUME_ALIGNED(a);
ASSUME_ALIGNED(b);
ASSUME_ALIGNED(c);
PRAGMA_SIMD
for (int i = 0; i < 2048; ++i) {
if (c[i] > 0) {
a[i] = b[i];
} else {
a[i] = 0.0;
}
}
}
void foo2(double * restrict a, const double * restrict b, …
Run Code Online (Sandbox Code Playgroud) simd c99 variable-length-array restrict-qualifier auto-vectorization