Function overloading - c++

I found this code , and i m not sure that whether overloading should happen or not.
void print( int (*arr)[6], int size );
void print( int (*arr)[5], int size );
what happens if I pass pointer to an array of 4 elements , to it should come...
any thread will be helpful.

Overloading will happen, and passing the pointer to the array of 4 int's will not match either function. It's clearer if you write them as the equivalent form:
void print( int arr[][6], int size );
void print( int arr[][5], int size );
An N×4 array can be decayed to a pointer to array of 4 int's. And it's well known that 2D arrays having different 2nd dimensions are incompatible.

KennyTM's answer is the correct one. Here's an additional thought, though, based on the fact that your question comes with a C++ tag. In C++, you can use templates with non-type arguments to find out array dimensions:
#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;
}

The call would be ambiguous as none of the two overloads would be able to convert to int (*arr)[4]. You need to pass in an element of 5 or 6 elements explicitly.
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 that helps.

Related

Why is the C++ compiler complaining here? [duplicate]

Why isn't the size of an array sent as a parameter the same as within main?
#include <stdio.h>
void PrintSize(int p_someArray[10]);
int main () {
int myArray[10];
printf("%d\n", sizeof(myArray)); /* As expected, 40 */
PrintSize(myArray);/* Prints 4, not 40 */
}
void PrintSize(int p_someArray[10]){
printf("%d\n", sizeof(p_someArray));
}
An array-type is implicitly converted into pointer type when you pass it in to a function.
So,
void PrintSize(int p_someArray[10]) {
printf("%zu\n", sizeof(p_someArray));
}
and
void PrintSize(int *p_someArray) {
printf("%zu\n", sizeof(p_someArray));
}
are equivalent. So what you get is the value of sizeof(int*)
It's a pointer, that's why it's a common implementation to pass the size of the array as a second parameter to the function
As others have stated, arrays decay to pointers to their first element when used as function parameters. It's also worth noting that sizeof does not evaluate the expression and does not require parentheses when used with an expression, so your parameter isn't actually being used at all, so you may as well write the sizeof with the type rather than the value.
#include <stdio.h>
void PrintSize1 ( int someArray[][10] );
void PrintSize2 ( int someArray[10] );
int main ()
{
int myArray[10];
printf ( "%d\n", sizeof myArray ); /* as expected 40 */
printf ( "%d\n", sizeof ( int[10] ) ); /* requires parens */
PrintSize1 ( 0 ); /* prints 40, does not evaluate 0[0] */
PrintSize2 ( 0 ); /* prints 40, someArray unused */
}
void PrintSize1 ( int someArray[][10] )
{
printf ( "%d\n", sizeof someArray[0] );
}
void PrintSize2 ( int someArray[10] )
{
printf ( "%d\n", sizeof ( int[10] ) );
}
So, you will need to pass the lenght of the array as a second parameter. When you are writing code, in which you both declare an array of constant size, and later pass that array to a function, it is a pain to have the array-length constant show up several places in your code...
K&R to the rescue:
#define N_ELEMENTS(array) (sizeof(array)/sizeof((array)[0]))
So now you can do e.g:
int a[10];
...
myfunction(a, N_ELEMENTS(a));
The behavior you found is actually a big wart in the C language. Whenever you declare a function that takes an array parameter, the compiler ignores you and changes the parameter to a pointer. So these declarations all behave like the first one:
void func(int *a)
void func(int a[])
void func(int a
typedef int array_plz[5];
void func(array_plz a)
a will be a pointer to int in all four cases. If you pass an array to func, it will immediately decay into a pointer to its first element. (On a 64-bit system, a 64-bit pointer is twice as large as a 32-bit int, so your sizeof ratio returns 2.)
The only purpose of this rule is to maintain backwards compatibility with historical compilers that did not support passing aggregate values as function arguments.
This does not mean that it’s impossible to pass an array to a function. You can get around this wart by embedding the array into a struct (this is basically the purpose of C++11’s std::array):
struct array_rly {
int a[5];
};
void func(struct array_rly a)
{
printf("%zd\n", sizeof(a.a)/sizeof(a.a[0])); /* prints 5 */
}
or by passing a pointer to the array:
void func(const int (*a)[5])
{
printf("%zd\n", sizeof(*a)/sizeof((*a)[0])); /* prints 5 */
}
In case the array size isn’t a compile-time constant, you can use the pointer-to-array technique with C99 variable-length arrays:
void func(int n, const int (*a)[n])
{
printf("%zd\n", sizeof(*a)/sizeof((*a)[0])); /* prints n */
}
Because arrays decay into pointers when they are passed as parameters. This is how C works, although you can pass "arrays" in C++ by reference and overcome this issue. Note that you can pass arrays of different sizes to this function:
// 10 is superfluous here! You can pass an array of different size!
void PrintSize(int p_someArray[10]);
In c++ you can pass an array by reference for this very purpose :
void foo(int (&array)[10])
{
std::cout << sizeof(array) << "\n";
}
In the C language, there is no method to determine the
size of an unknown array, so the quantity needs to
be passed as well as a pointer to the first element.
You can't pass arrays to functions.
If you really wanted to print the size, you could pass a pointer to an array, but it won't be generic at all as you need to define the array size for the function as well.
#include <stdio.h>
void PrintSize(int (*p_anArray)[10]);
int main(void) {
int myArray[10];
printf("%d\n", sizeof(myArray)); /* as expected 40 */
PrintSize(&myArray);/* prints 40 */
}
void PrintSize(int (*p_anArray)[10]){
printf("%d\n", (int) sizeof(*p_anArray));
}
The behavior is by design.
Same syntax in function parameter declaration means completely different thing than in local variable definition.
The reason is described in other answers.
In C language when you pass the array as an argument to the function , it is automatically converted into pointer ,array passing from one function other function is know as call by reference . That is the reason the called function only receives the pointer which point to the first element of function This is the reason
fun(int a[]) is similar to fun(int *a) ;
so when you print the size of array it will print the size of first element.
In 'C' programming languange 'sizeof()' is the operator and he returns the size of the object in bytes.Argument of the 'sizeof()' operator must be a left-value type(integer,float number,struct,array).So if you want to know the size of an array in bytes you can do it very simple.Just use the 'sizeof()' operator and for his argument use the array name.For example:
#include <stdio.h>
main(){
int n[10];
printf("Size of n is: %d \n", sizeof(n));
}
Output on 32 bit system will be: Size of n is: 40.Because ineteger on 32 system is 4bytes.On 64x it is 8bytes.In this case we have 10 integers declared in one array.So the result is '10 * sizeof(int)'.
Some tips:
If we have an array declared like this one 'int n[]={1, 2, 3, ...155..};'.
So we want to know how many elements are stored in this array.
Use this alghorithm:
sizeof(name_of_the_array) / sizeof(array_type)
Code: #include
main(){
int n[] = { 1, 2, 3, 44, 6, 7 };
printf("Number of elements: %d \n", sizeof(n) / sizeof(int));
return 0;
}
Arrays are only loosely sized. For the most part, an array is a pointer to memory. The size in your declaration only tells the compiler how much memory to allocate for the array - it's not associated with the type, so sizeof() has nothing to go on.

How to make size output for array the same from inside function compared to main? [duplicate]

Why isn't the size of an array sent as a parameter the same as within main?
#include <stdio.h>
void PrintSize(int p_someArray[10]);
int main () {
int myArray[10];
printf("%d\n", sizeof(myArray)); /* As expected, 40 */
PrintSize(myArray);/* Prints 4, not 40 */
}
void PrintSize(int p_someArray[10]){
printf("%d\n", sizeof(p_someArray));
}
An array-type is implicitly converted into pointer type when you pass it in to a function.
So,
void PrintSize(int p_someArray[10]) {
printf("%zu\n", sizeof(p_someArray));
}
and
void PrintSize(int *p_someArray) {
printf("%zu\n", sizeof(p_someArray));
}
are equivalent. So what you get is the value of sizeof(int*)
It's a pointer, that's why it's a common implementation to pass the size of the array as a second parameter to the function
As others have stated, arrays decay to pointers to their first element when used as function parameters. It's also worth noting that sizeof does not evaluate the expression and does not require parentheses when used with an expression, so your parameter isn't actually being used at all, so you may as well write the sizeof with the type rather than the value.
#include <stdio.h>
void PrintSize1 ( int someArray[][10] );
void PrintSize2 ( int someArray[10] );
int main ()
{
int myArray[10];
printf ( "%d\n", sizeof myArray ); /* as expected 40 */
printf ( "%d\n", sizeof ( int[10] ) ); /* requires parens */
PrintSize1 ( 0 ); /* prints 40, does not evaluate 0[0] */
PrintSize2 ( 0 ); /* prints 40, someArray unused */
}
void PrintSize1 ( int someArray[][10] )
{
printf ( "%d\n", sizeof someArray[0] );
}
void PrintSize2 ( int someArray[10] )
{
printf ( "%d\n", sizeof ( int[10] ) );
}
So, you will need to pass the lenght of the array as a second parameter. When you are writing code, in which you both declare an array of constant size, and later pass that array to a function, it is a pain to have the array-length constant show up several places in your code...
K&R to the rescue:
#define N_ELEMENTS(array) (sizeof(array)/sizeof((array)[0]))
So now you can do e.g:
int a[10];
...
myfunction(a, N_ELEMENTS(a));
The behavior you found is actually a big wart in the C language. Whenever you declare a function that takes an array parameter, the compiler ignores you and changes the parameter to a pointer. So these declarations all behave like the first one:
void func(int *a)
void func(int a[])
void func(int a
typedef int array_plz[5];
void func(array_plz a)
a will be a pointer to int in all four cases. If you pass an array to func, it will immediately decay into a pointer to its first element. (On a 64-bit system, a 64-bit pointer is twice as large as a 32-bit int, so your sizeof ratio returns 2.)
The only purpose of this rule is to maintain backwards compatibility with historical compilers that did not support passing aggregate values as function arguments.
This does not mean that it’s impossible to pass an array to a function. You can get around this wart by embedding the array into a struct (this is basically the purpose of C++11’s std::array):
struct array_rly {
int a[5];
};
void func(struct array_rly a)
{
printf("%zd\n", sizeof(a.a)/sizeof(a.a[0])); /* prints 5 */
}
or by passing a pointer to the array:
void func(const int (*a)[5])
{
printf("%zd\n", sizeof(*a)/sizeof((*a)[0])); /* prints 5 */
}
In case the array size isn’t a compile-time constant, you can use the pointer-to-array technique with C99 variable-length arrays:
void func(int n, const int (*a)[n])
{
printf("%zd\n", sizeof(*a)/sizeof((*a)[0])); /* prints n */
}
Because arrays decay into pointers when they are passed as parameters. This is how C works, although you can pass "arrays" in C++ by reference and overcome this issue. Note that you can pass arrays of different sizes to this function:
// 10 is superfluous here! You can pass an array of different size!
void PrintSize(int p_someArray[10]);
In c++ you can pass an array by reference for this very purpose :
void foo(int (&array)[10])
{
std::cout << sizeof(array) << "\n";
}
In the C language, there is no method to determine the
size of an unknown array, so the quantity needs to
be passed as well as a pointer to the first element.
You can't pass arrays to functions.
If you really wanted to print the size, you could pass a pointer to an array, but it won't be generic at all as you need to define the array size for the function as well.
#include <stdio.h>
void PrintSize(int (*p_anArray)[10]);
int main(void) {
int myArray[10];
printf("%d\n", sizeof(myArray)); /* as expected 40 */
PrintSize(&myArray);/* prints 40 */
}
void PrintSize(int (*p_anArray)[10]){
printf("%d\n", (int) sizeof(*p_anArray));
}
The behavior is by design.
Same syntax in function parameter declaration means completely different thing than in local variable definition.
The reason is described in other answers.
In C language when you pass the array as an argument to the function , it is automatically converted into pointer ,array passing from one function other function is know as call by reference . That is the reason the called function only receives the pointer which point to the first element of function This is the reason
fun(int a[]) is similar to fun(int *a) ;
so when you print the size of array it will print the size of first element.
In 'C' programming languange 'sizeof()' is the operator and he returns the size of the object in bytes.Argument of the 'sizeof()' operator must be a left-value type(integer,float number,struct,array).So if you want to know the size of an array in bytes you can do it very simple.Just use the 'sizeof()' operator and for his argument use the array name.For example:
#include <stdio.h>
main(){
int n[10];
printf("Size of n is: %d \n", sizeof(n));
}
Output on 32 bit system will be: Size of n is: 40.Because ineteger on 32 system is 4bytes.On 64x it is 8bytes.In this case we have 10 integers declared in one array.So the result is '10 * sizeof(int)'.
Some tips:
If we have an array declared like this one 'int n[]={1, 2, 3, ...155..};'.
So we want to know how many elements are stored in this array.
Use this alghorithm:
sizeof(name_of_the_array) / sizeof(array_type)
Code: #include
main(){
int n[] = { 1, 2, 3, 44, 6, 7 };
printf("Number of elements: %d \n", sizeof(n) / sizeof(int));
return 0;
}
Arrays are only loosely sized. For the most part, an array is a pointer to memory. The size in your declaration only tells the compiler how much memory to allocate for the array - it's not associated with the type, so sizeof() has nothing to go on.

Passing arrays to functions, what is the difference between these two approaches?

In the example below, both functions return the same result. Can someone please explain what the difference is between them?
#include <iostream>
void func1( int (&a)[4]) {
int b = a[3];
std::cout << b << std::endl;
}
void func2( int a[4]) {
int b = a[3];
std::cout << b << std::endl;
}
int main()
{
int b[4] = {3,2,3,4};
func1(b);
func2(b);
return 0;
}
In func2, int a[4] is equivalent to int *a, in other words, 4 does not matter at all. You can pass an array of any size to to this function.
However, for func1, you have to pass it an array of size 4 or you will get a compilation error.
For example, if you feed func1 an array of size 8, you will get this compliation error,
main.cpp:26:12: error: invalid initialization of reference of type ‘int (&)[4]’ from expression of type ‘int [8]’ regardless of what the array size you feed to the function is.
Also, if you print the output of sizeof(a) function in func1, it will return the size of the input array in bytes, in this case, 16=4*4 bytes. For func2, it retunrs the size of a, which is a pointer to int (in my case that size is 8 bytes).
The first one won't accept any type except a reference to an array of 4 int elements while the second will accept a pointer to int or an array of unspecified size of int because it will be passed as an array.
Note also the first approach doesn't accept temporaries arguments so you can't do something like :
func1({1, 2, 3, 4});
But if you want to use temporaries you could write :
void func1( int (&&a)[4])

How come even though arrays decay to POINTERS, its fine to keep the parameter of the function as an ARRAY?

please excuse my bad english,
let me clarify, here is an example,
this is our main :
main()
{
int a1 []= {1,2,3,4,5,6,7,8,9} ;
int size = sizeof(a1) /sizeof(a1[0]) ;
point (a1 , size);
return 0 ;
}
and this is the function:
void point(int a[] , int size)
{
int i ;
for (i = 0 ; i<size ; i++)
printf("%d\n", a[i])) ;
}
From my knowledge, when an array is passed as an argument to a function, we are actually sending a pointer to the first element to the array..
With that being said, how come the function "point"'s parameter is an ARRAY variable, NOT a POINTER variable...?
The reason I thought this was weird, so for example in main we pass int* to some function :
int* a = &b ;
point2(a) ;
The function:
void point2 (int a) // this would be invalid, it has to be int* a
{
.
.
}
We would have to specify that the function receives a pointer, How are arrays an exception?
PLEASE NOTE: I do understand that arrays decay to pointers; that's why my question never was "why can we send arrays as arguments, to functions that have pointers of that same type?". My question is, "How come even though arrays decay to POINTERS, its fine to keep the parameter of the function as an ARRAY?". Hope it is clear how this is different that the first question.
Thank you!
The language specifications of both C and C++ state that a function parameter of type array of T is adjusted to type pointer to T. So these function declarations are one and the same:
void foo(int a[42]);
void foo(int a[]);
void foo(int* a);
All of these will accept a pointer parameter, be it the result of an array decay or not.
Syntactic sugar.
Like juanchopanza noticed, in function arguments it's equivalent to have an array or a pointer.
For fun, try this:
void foo(int a[42])
{
printf("%zu\n", sizeof(a));
}
int main(int argc, char **argv)
{
int a[42];
printf("%zu\n", sizeof(a));
foo(a);
}

Different size of fixed array (c++) [duplicate]

Why isn't the size of an array sent as a parameter the same as within main?
#include <stdio.h>
void PrintSize(int p_someArray[10]);
int main () {
int myArray[10];
printf("%d\n", sizeof(myArray)); /* As expected, 40 */
PrintSize(myArray);/* Prints 4, not 40 */
}
void PrintSize(int p_someArray[10]){
printf("%d\n", sizeof(p_someArray));
}
An array-type is implicitly converted into pointer type when you pass it in to a function.
So,
void PrintSize(int p_someArray[10]) {
printf("%zu\n", sizeof(p_someArray));
}
and
void PrintSize(int *p_someArray) {
printf("%zu\n", sizeof(p_someArray));
}
are equivalent. So what you get is the value of sizeof(int*)
It's a pointer, that's why it's a common implementation to pass the size of the array as a second parameter to the function
As others have stated, arrays decay to pointers to their first element when used as function parameters. It's also worth noting that sizeof does not evaluate the expression and does not require parentheses when used with an expression, so your parameter isn't actually being used at all, so you may as well write the sizeof with the type rather than the value.
#include <stdio.h>
void PrintSize1 ( int someArray[][10] );
void PrintSize2 ( int someArray[10] );
int main ()
{
int myArray[10];
printf ( "%d\n", sizeof myArray ); /* as expected 40 */
printf ( "%d\n", sizeof ( int[10] ) ); /* requires parens */
PrintSize1 ( 0 ); /* prints 40, does not evaluate 0[0] */
PrintSize2 ( 0 ); /* prints 40, someArray unused */
}
void PrintSize1 ( int someArray[][10] )
{
printf ( "%d\n", sizeof someArray[0] );
}
void PrintSize2 ( int someArray[10] )
{
printf ( "%d\n", sizeof ( int[10] ) );
}
So, you will need to pass the lenght of the array as a second parameter. When you are writing code, in which you both declare an array of constant size, and later pass that array to a function, it is a pain to have the array-length constant show up several places in your code...
K&R to the rescue:
#define N_ELEMENTS(array) (sizeof(array)/sizeof((array)[0]))
So now you can do e.g:
int a[10];
...
myfunction(a, N_ELEMENTS(a));
The behavior you found is actually a big wart in the C language. Whenever you declare a function that takes an array parameter, the compiler ignores you and changes the parameter to a pointer. So these declarations all behave like the first one:
void func(int *a)
void func(int a[])
void func(int a
typedef int array_plz[5];
void func(array_plz a)
a will be a pointer to int in all four cases. If you pass an array to func, it will immediately decay into a pointer to its first element. (On a 64-bit system, a 64-bit pointer is twice as large as a 32-bit int, so your sizeof ratio returns 2.)
The only purpose of this rule is to maintain backwards compatibility with historical compilers that did not support passing aggregate values as function arguments.
This does not mean that it’s impossible to pass an array to a function. You can get around this wart by embedding the array into a struct (this is basically the purpose of C++11’s std::array):
struct array_rly {
int a[5];
};
void func(struct array_rly a)
{
printf("%zd\n", sizeof(a.a)/sizeof(a.a[0])); /* prints 5 */
}
or by passing a pointer to the array:
void func(const int (*a)[5])
{
printf("%zd\n", sizeof(*a)/sizeof((*a)[0])); /* prints 5 */
}
In case the array size isn’t a compile-time constant, you can use the pointer-to-array technique with C99 variable-length arrays:
void func(int n, const int (*a)[n])
{
printf("%zd\n", sizeof(*a)/sizeof((*a)[0])); /* prints n */
}
Because arrays decay into pointers when they are passed as parameters. This is how C works, although you can pass "arrays" in C++ by reference and overcome this issue. Note that you can pass arrays of different sizes to this function:
// 10 is superfluous here! You can pass an array of different size!
void PrintSize(int p_someArray[10]);
In c++ you can pass an array by reference for this very purpose :
void foo(int (&array)[10])
{
std::cout << sizeof(array) << "\n";
}
In the C language, there is no method to determine the
size of an unknown array, so the quantity needs to
be passed as well as a pointer to the first element.
You can't pass arrays to functions.
If you really wanted to print the size, you could pass a pointer to an array, but it won't be generic at all as you need to define the array size for the function as well.
#include <stdio.h>
void PrintSize(int (*p_anArray)[10]);
int main(void) {
int myArray[10];
printf("%d\n", sizeof(myArray)); /* as expected 40 */
PrintSize(&myArray);/* prints 40 */
}
void PrintSize(int (*p_anArray)[10]){
printf("%d\n", (int) sizeof(*p_anArray));
}
The behavior is by design.
Same syntax in function parameter declaration means completely different thing than in local variable definition.
The reason is described in other answers.
In C language when you pass the array as an argument to the function , it is automatically converted into pointer ,array passing from one function other function is know as call by reference . That is the reason the called function only receives the pointer which point to the first element of function This is the reason
fun(int a[]) is similar to fun(int *a) ;
so when you print the size of array it will print the size of first element.
In 'C' programming languange 'sizeof()' is the operator and he returns the size of the object in bytes.Argument of the 'sizeof()' operator must be a left-value type(integer,float number,struct,array).So if you want to know the size of an array in bytes you can do it very simple.Just use the 'sizeof()' operator and for his argument use the array name.For example:
#include <stdio.h>
main(){
int n[10];
printf("Size of n is: %d \n", sizeof(n));
}
Output on 32 bit system will be: Size of n is: 40.Because ineteger on 32 system is 4bytes.On 64x it is 8bytes.In this case we have 10 integers declared in one array.So the result is '10 * sizeof(int)'.
Some tips:
If we have an array declared like this one 'int n[]={1, 2, 3, ...155..};'.
So we want to know how many elements are stored in this array.
Use this alghorithm:
sizeof(name_of_the_array) / sizeof(array_type)
Code: #include
main(){
int n[] = { 1, 2, 3, 44, 6, 7 };
printf("Number of elements: %d \n", sizeof(n) / sizeof(int));
return 0;
}
Arrays are only loosely sized. For the most part, an array is a pointer to memory. The size in your declaration only tells the compiler how much memory to allocate for the array - it's not associated with the type, so sizeof() has nothing to go on.