Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

is a c++ array of size N a distinct type

I thought that

int a1[5];

and

int a2[6];

were distinct types.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

But

void foo(int a[5]){};
void foo(int a[6]){};

will not compile saying that they are duplicated definitions of foo (ie foo(int *a))

I was very surprised by this. One of the reasons I saw given for why VLAs are not allowed in the c++ standard is because they break the type system.

I was also surprised to find c doing the same thing.

void foo(int a[4]){
   printf("sz=%ld", sizeof(a));
}

reports a pointer size. I expected it to report 4*sizeof(int) (and only accept a variable of type int[4] to be accepted as a call argument)

>Solution :

Yes, they are distinct types, this can be confirmed with:

int a[5];
int b[6];
static_assert(!std::is_same_v<decltype(a), decltype(b)>);

Your problem is that in function parameter lists, arrays are silently replaced with pointers, so both void foo(int a[5]) and void foo(int a[6]) end up as void foo(int *a).

This only happens to arrays, as opposed to e.g. references to arrays, so void foo(int (&a)[5]) would work (or int (*a)[5] in C).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading