问题
Can anyone enlighten me as to why I should bother to specify the size of a C array argument in a function header? For example:
void foo (int iz[6]) { iz[42] = 43; }
With:
int is[2] = {1,2,3};
we get a useful error. Perhaps it helps with commenting/documentation?
回答1:
Can anyone enlighten me as to why I should bother to specify the size of a C array argument in a function header? For example:
void foo (const char sz[6]) { sz[42] = 43; }
IMO, you shouldn't. When you try to pass an array to a function, what's really passed is a pointer to the beginning of the array. Since what the function receives will be a pointer, it's better to write it to make that explicit:
void foo(char const *sz)
Then, since it's now clear that the function has been given no clue of the size, add that as a separate parameter:
void foo(char const *sz, size_t size)
回答2:
The only meaningful reason to do that is for documentation purposes - to tell the future users that functions expect to receive an array of at least that many elements. But even that is a matter of convention - something that you have to agree upon with other users in advance. The language (the compiler) ignores that size anyway. Your function declaration is equivalent to void foo(int iz[])
and to void foo(int *iz)
.
The only way to make it somewhat meaningful for the compiler is to declare it as
void foo (int iz[static 6])
which acts as a promise to the compiler that the array will have at least 6 elements, meaning that the compiler will be able to optimize that code using that assumption. Moreover, if you really want to adopt the convention mentioned above, it makes more sense to declare array parameter sizes with static
specifically, since the language explicitly defines the semantics of this construct.
What you mean by "we get a useful error" is not clear to me. The code
int is[2] = {1,2,3};
is[42] = 42;
does not contain any constraint violations. It produces undefined behavior, but it is not required to produce a diagnostic message during compilation. In other words, no, we don't get any "useful error" from this.
回答3:
It's a comment. Arrays are demoted to pointers in function parameters. Comments can still be useful however, even if the compiler doesn't read them.
回答4:
It is a useful comment when you want to tell to client code that it must pass an array of defined size, i.e:
void foo(const char bar[5]);
/* It is expected that foo function receives an array of size 5 */
Yet, documentation doesn't replace in code checks:
void foo(const char bar[5])
{
if (!bar) error();
if (strlen(bar) != 4) error();
/* ... */
}
来源:https://stackoverflow.com/questions/5187224/why-should-i-declare-a-c-array-parameters-size-in-a-function-header