Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
136 views
in Technique[技术] by (71.8m points)

c++ - Why can one specify the size of an array in a function parameter?

I don't understand why the following example compiles and works:

void printValues(int nums[3], int length) {
    for(int i = 0; i < length; i++) 
        std::cout << nums[i] << " ";
    std::cout << '
';
}

It seems that the size of 3 is completely ignored but putting an invalid size results in a compile error. What is going on here?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In C++ (as well as in C), parameters declared with array type always immediately decay to pointer type. The following three declarations are equivalent

void printValues(int nums[3], int length);
void printValues(int nums[], int length);
void printValues(int *nums, int length);

I.e. the size does not matter. Yet, it still does not mean that you can use an invalid array declaration there, i.e. it is illegal to specify a negative or zero size, for example.

(BTW, the same applies to parameters of function type - it immediately decays to pointer-to-function type.)

If you want to enforce array size matching between arguments and parameters, use pointer- or reference-to-array types in parameter declarations

void printValues(int (&nums)[3]);
void printValues(int (*nums)[3]);

Of course, in this case the size will become a compile-time constant and there's no point of passing length anymore.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...