In C and C , function signatures may include array lengths in square brackets, such as int a[1]. However, this behavior has puzzled developers, as the lengths seem to have no practical effect.
Consider the following example:
#include <iostream> int dis(char a[1]) { int length = strlen(a); char c = a[2]; return length; } int main() { char b[4] = "abc"; int c = dis(b); cout << c; return 0; }
In this code, the function dis declares an array parameter with a length of 1 (a[1]), but accessing a[2] is still possible. This raises the question: why do compilers allow array lengths in function signatures if they are not enforced?
The answer lies in the unique behavior of array passing in C/C . Unlike many other languages, C and C do not allow direct passing of arrays to functions. Instead, a pointer to the first element of the array is passed.
As a result, the array length specified in the function signature becomes irrelevant. The length information is not included in the pointer, so the compiler simply ignores the length in the brackets.
This behavior stems from a decision made during the early stages of C development in the 1970s. While it has caused confusion over the years, the syntax remains prevalent in both C and C .
This quirk of array passing has several implications:
The above is the detailed content of Why Are Array Lengths in C/C Function Signatures Ignored by the Compiler?. For more information, please follow other related articles on the PHP Chinese website!