Parameter declaration [] and * (array)
Between formal parameters in a function definition, like:
void change (int *s)
{
s[0] = 42;
}
And another definition:
void change (int s[])
{
s[0] = 42;
}
They are the same I assume, as *(a+0)
is the same as a[0]
.
Is there a reason to prefer one over the another? Please note, the preference pertains to cod开发者_如何学Cing style.
Yes, they are exactly the same. All function parameters declared as arrays are adjusted to the corresponding pointer type.
Personally, I prefer the former which actually makes it look like a pointer declaration which is what it is in both cases.
I prefer the second one because it is then clear that you intend to use s
as an array. (even though it is a pointer technically)
I think it is just another subjective thing though.
There is one case where they can be different, in the current C language. C99 allows the following:
void change (int s[static 2])
{
s[0] = 42;
}
where the [static 2]
imposes a constraint on the interface of the function that the pointer passed must be such that s[0]
and s[1]
access valid objects of type int
. In particular, the interface does not permit NULL
pointers.
Note that [static 1]
is a convenient way to specify simply that the pointer must point to a valid object.
精彩评论