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

后端 未结 10 1409
终归单人心
终归单人心 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:36

    This is a well-known "feature" of C, passed over to C++ because C++ is supposed to correctly compile C code.

    Problem arises from several aspects:

    1. An array name is supposed to be completely equivalent to a pointer.
    2. C is supposed to be fast, originally developerd to be a kind of "high-level Assembler" (especially designed to write the first "portable Operating System": Unix), so it is not supposed to insert "hidden" code; runtime range checking is thus "forbidden".
    3. Machine code generrated to access a static array or a dynamic one (either in the stack or allocated) is actually different.
    4. Since the called function cannot know the "kind" of array passed as argument everything is supposed to be a pointer and treated as such.

    You could say arrays are not really supported in C (this is not really true, as I was saying before, but it is a good approximation); an array is really treated as a pointer to a block of data and accessed using pointer arithmetic. Since C does NOT have any form of RTTI You have to declare the size of the array element in the function prototype (to support pointer arithmetic). This is even "more true" for multidimensional arrays.

    Anyway all above is not really true anymore :p

    Most modern C/C++ compilers do support bounds checking, but standards require it to be off by default (for backward compatibility). Reasonably recent versions of gcc, for example, do compile-time range checking with "-O3 -Wall -Wextra" and full run-time bounds checking with "-fbounds-checking".

提交回复
热议问题