CC++语法::数组名退化(array decaying)

参考:

CSDN::C/C++中数组名退化为指针的情况

*::What is array decaying?

起因

笔者在写memset的时候总想偷一点懒(因为我们一般都是为了清零),于是一般都会有下面的写法:

#include <iostream>
#include <string.h>
#define memset(_) memset( (_) ,0,sizeof (_) )
using namespace std;
const int MAXN = 1005;
int x[MAXN];

int main(){
    ios::sync_with_stdio(0);
    cin.tie(0);cout.tie(0);

    x[15]=111;
    memset(x);
    cout<<x[15]<<endl;

    return 0;
}


感觉还挺不错的,但是总以来宏定义好像不是很好,那我们试试来写一个函数,仔细一想,好像不太好办。因为,如果数组名被传入了函数,它会退化成一个对应的指针变量,而这一点因为我们大学的语言老师没有可以提到过,所以给我留下了很多迷惑的空间。

经过研究,我写出了下面这样的等价代码:

#include <iostream>
#include <string.h>
//#define memset(_) memset( (_) ,0,sizeof (_) )
using namespace std;
const int MAXN = 1005;
int x[MAXN];

inline void memset(auto (&_)[MAXN]){
    memset(_,0,sizeof _);
}

int main(){
    ios::sync_with_stdio(0);
    cin.tie(0);cout.tie(0);

    x[15]=111;
    memset(x);
    cout<<x[15]<<endl;

    return 0;
}

哇,一下子就变得好糟糕,而且这还是需要已知数组大小的情况下才可以实现的。

暂时没有更好的解决办法,还是用宏定义吧(真香)。