我偶然发现了一个代码,其中变量似乎是在函数的参数列表之后声明的。我不知道这是可能的。
在代码中,int r
和int *a
在arr2int
的参数列表之后被声明。这如何影响a
的局部变量r
和arr2int
?
我想要理解代码的实际原因是因为如果我在a[1] = 1
上运行我的linux x86 //MARKER
时arr2int
被称为第一次。
但是,如果我让它运行在基于ARM的omap4开发板a[1]=0
上,我不知道为什么会有区别。
有人可以对此发表评论吗?
long arr2int(a,r)
int r;
int *a;
{
int i;
long mul, result = 0, temp;
//MARKER
for (i=1; i<=r; i++) {
mul = 1;
temp = a[i]-1;
while (temp--)
mul = mul << 1;
result += mul;
}
return(result);
}
和调用方法:
void generateEncodingTable(){
register int i,j;
long temp;
int seed = 133757;
printf("\n[I] - Generating Encoding Table\n");
for (pattern = 0; pattern < 4096; pattern++) {
temp = pattern << 11; /* multiply information by X^{11} */
encoding_table[pattern] = temp + get_syndrome(temp);/* add redundancy */
}
decoding_table[0] = 0;
decoding_table[1] = 1;
temp = 1;
for (i=2; i<= 23; i++) {
temp *= 2;
decoding_table[get_syndrome(temp)] = temp;
}
a[1] = 1; a[2] = 2;
temp = arr2int(a,2);
decoding_table[get_syndrome(temp)] = temp;
for (i=1; i<253; i++) {
nextcomb(23,2,a);
temp = arr2int(a,2);
decoding_table[get_syndrome(temp)] = temp;
}
a[1] = 1; a[2] = 2; a[3] = 3;
temp = arr2int(a,3);
decoding_table[get_syndrome(temp)] = temp;
for (i=1; i<1771; i++) {
nextcomb(23,3,a);
temp = arr2int(a,3);
decoding_table[get_syndrome(temp)] = temp;
}
}
这是一个古老的符号,称为K&R(Kernighan&Ritchie,继Brian Kernighan和Dennis Ritchie之后)用于声明函数的符号。如果您的编译器支持它,您可以使用它,它与使用ANSI表示法声明函数相同。
正如其他人所说,这是功能编码的早期风格。
以下是这种风格的陷阱。请注意,传递的参数没有类型检查。它可以解释您的运行时差异。
假设您声明一个函数
int foo(a,b,c);
所有编译器在那一点看到的是一个名为“foo”的函数,它接受3个参数并返回一个int
。因此,使用检查仅限于此。
让我们假设sizeof(short)
<sizeof(int)
<sizeof(long)
,函数定义为
int foo(a,b,c)
int a;
long b;
int c;
{ /* code body */ }
请注意foo
的以下用法
int d,e,f;
d = foo(1,2L,3);
e = foo((short)1,2L,3);
f = foo(1,2,3);
第一个用法很好,正确的大小整数传递给foo
。
第二次使用也很好。在调用之前,第一个参数被提升为int
大小,就像printf("%d", (short)2)
在传递给(short)2
之前将int
提升为printf()
。
第3个是一个问题,因为编译器不知道第二个参数需要是long
。因此,传递给foo
的数据未正确传递。 - > UB
这是一个旧的C语法。如果您的编译器可以吞下它,那么它应该像您使用正常的ANSI方式声明函数一样工作。
这是K&R C,即由Brian Kernighan和Dennis Ritchie编写的第一版C语言编程所描述的C语言。第二版已转向ANSI C(C89)。
您应该始终使用ANSI C样式:
Rationale for International Standard - Programming Languages C 6.11.6函数声明符
使用“旧式”功能声明和定义,即不使用原型的传统风格,过时的表征标志着委员会的意图,即新的原型风格最终将取代旧风格。
这种情况的要点是,新语法解决了K&R中定义的语言的一些最明显的缺点,即新风格在每个方面都优于旧风格。
它只是一种声明函数参数类型的方法:
void func (first_param, second_param)
int first_param;
int second_param;
{
// ...
}
等于
void func (int first_param, int second_param)
{
// ...
}