Why do C and C++ compilers allow array lengths in function signatures when they're never enforced?

后端 未结 10 1431
终归单人心
终归单人心 2020-11-22 06:59

This is what I found during my learning period:

#include
using namespace std;
int dis(char a[1])
{
    int length = strlen(a);
    char c = a         


        
10条回答
  •  长发绾君心
    2020-11-22 07:43

    One thing that hasn't been answered yet is the actual question.

    The answers already given explain that arrays cannot be passed by value to a function in either C or C++. They also explain that a parameter declared as int[] is treated as if it had type int *, and that a variable of type int[] can be passed to such a function.

    But they don't explain why it has never been made an error to explicitly provide an array length.

    void f(int *); // makes perfect sense
    void f(int []); // sort of makes sense
    void f(int [10]); // makes no sense
    

    Why isn't the last of these an error?

    A reason for that is that it causes problems with typedefs.

    typedef int myarray[10];
    void f(myarray array);
    

    If it were an error to specify the array length in function parameters, you would not be able to use the myarray name in the function parameter. And since some implementations use array types for standard library types such as va_list, and all implementations are required to make jmp_buf an array type, it would be very problematic if there were no standard way of declaring function parameters using those names: without that ability, there could not be a portable implementation of functions such as vprintf.

提交回复
热议问题