+ 3

Why this c++ function can return array’s size correctly?

This is my code. template < typename T, uint32_t SZ > constexpr uint32_t len(const T(&array)[SZ]) { return SZ; } when I pass the argument like this. int a[]={1,2,3,4,5,6}; len(a) == 6; It return a’s size correctly. Can someone explain it? https://code.sololearn.com/c8NcavwgzEB9/?ref=app

28th Aug 2018, 12:29 PM
RainStorm
RainStorm - avatar
3 Answers
+ 2
why dont use for loop ? for (int x =0;x<6 ;x++) { cout << a[x];
28th Aug 2018, 1:12 PM
Muhamad Fathi Zuhaili
Muhamad Fathi Zuhaili - avatar
+ 2
because the size is six is not 5 arrays are starting by their index from 0.
30th Aug 2018, 2:42 PM
Driss Aharik
Driss Aharik - avatar
+ 1
It appears to be counting the number of elements on the array. I changed the type of array to float and added an additional item to the array. The process still returned the correct number of elements.
21st Oct 2018, 8:34 PM
Roger Greenlaw