由C/C++函数的参数列表中的数组长度所想

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

这个是由于,很久前的一次(其实也没多久),编程过程中发现这种情况

#include<iostream>
using namespace std;
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;
}  
函数dis中的参数a[1]后的数字1,根本不起作用,其实写2.3.4都可以,这也是很多人都知道的,本着探究的精神多想了一点,既然不起作用,那么为什么不禁止这种行为,依然还是到了stackoverflow(真的是神站)上提问,得到了众多大神的解答

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

这是一个比较好的回答

It is a quirk of the syntax for passing arrays to functions.

Actually it is not possible to pass an array in C. If you write syntax that looks like it should pass the array, what actually happens is that a pointer to the first element of the array is passed instead.

Since the pointer does not include any length information, the contents of your [] in the function formal parameter list are actually ignored.

The decision to allow this syntax was made in the 1970s and has caused much confusion ever since...

其他精彩的回答,具体可以看这里,就不搬过来了。。

http://stackoverflow.com/questions/22677415/why-do-c-and-c-compilers-allow-array-lengths-in-function-signatures-when-they

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值