Function overload

I found this code, and I'm not sure if the overload will happen or not.

void print( int (*arr)[6], int size ); void print( int (*arr)[5], int size ); 

what happens if i pass a pointer to an array of 4 elements so that it comes ...

any stream will be useful.

+4
source share
3 answers

Overloading will occur, and passing the pointer to an array of 4 int will not correspond to any of the functions. This is more understandable if you write them as an equivalent form:

 void print( int arr[][6], int size ); void print( int arr[][5], int size ); 

Array N & times; 4 can be decomposed into a pointer to an array of 4 int . And it is well known that 2D arrays having different 2-dimensional dimensions are incompatible.

+10
source

KennyTM's answer is correct. However, an additional thought arises here, based on the fact that your question comes with a C++ tag. In C ++, you can use templates with non-type arguments to determine the size of the array:

 #include <iostream> template< std::size_t N > void print(int (&arr)[N]) {std::cout << N << '\n';} int main() { int arr[6]; print(arr); return 0; } 
+6
source

The call will be ambiguous, since neither of the two overloads can be converted to int (*arr)[4] . You must explicitly pass an element of 5 or 6 elements.

VS2008 gives:

 error C2665: 'print' : none of the 2 overloads could convert all the argument types (2088): could be 'void print(int (*)[5],int)' (2093): or 'void print(int (*)[6],int)' while trying to match the argument list '(int (*)[4], int)' 

Hope this helps.

+1
source

Source: https://habr.com/ru/post/1306205/


All Articles