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

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

    First, C never checks array bounds. Doesn't matter if they are local, global, static, parameters, whatever. Checking array bounds means more processing, and C is supposed to be very efficient, so array bounds checking is done by the programmer when needed.

    Second, there is a trick that makes it possible to pass-by-value an array to a function. It is also possible to return-by-value an array from a function. You just need to create a new data type using struct. For example:

    typedef struct {
      int a[10];
    } myarray_t;
    
    myarray_t my_function(myarray_t foo) {
    
      myarray_t bar;
    
      ...
    
      return bar;
    
    }
    

    You have to access the elements like this: foo.a[1]. The extra ".a" might look weird, but this trick adds great functionality to the C language.

提交回复
热议问题