问题描述
Consider the following functions:
void func1(int unsized_array[]){}
void func2(int sized_array[10]){}
void func3(int *pointer){}
According to the result of:
std::cout << std::is_same<decltype(func1), decltype(func2)>::value << std::endl;
std::cout << std::is_same<decltype(func2), decltype(func3)>::value << std::endl;
std::cout << std::is_same<decltype(func3), decltype(func1)>::value << std::endl;
Types of these 3 functions is the same. Also inside the functionfunc2
, sizeof
operator does not provide the size of array elements all combined.
So what is the purpose of sized array as function argument (like func2
)?
Since array declarators generally may have size expressions (as when defining an array other than in a parameter or when declaring a parameter that contains an array as a sub-part, such as a pointer to an array), it would take more work to exclude it from the grammar than to leave it in harmlessly. (There are numerous constructions in C that can result in no effect, such as a statement expression with no side effects (
3*4;
), the left operand of a comma expression with no side effects, a function or loop with an empty body, and so on. It would take a lot of work to exclude things that have no effect from the language.)Array sizes in parameters do alter the meaning when the
static
keyword is present;void func2(int asd[static 10])
declares a function that must be passed a pointer to the first of at least ten elements, which is different from the meaning of the other declarations. (And this would compound the problem of excluding a size expression from the grammar of an array parameter declaration, as it would be necessary to ban a bare size but not one withstatic
.)The array size may be useful documentation to the function implementor and to the function user.
The array size is evaluated. If, for example, the definition is
void func2(int asd[printf("Hello")]) {}
, then "Hello" will be printed when the function is called. (Some compilers might not do this; the C standard is unclear on it.)A compiler could use the size expression to emit warnings if it sees the function uses more than the stated number of elements or a caller passes fewer than the stated number. (Clang 11 appears not to do the former and not to do the latter unless
static
is used.)
这篇关于将大小数组作为函数参数的目的是c和c++?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!