I have a doubt regarding the parameters, I have the following program:
#include <iostream>
using namespace std;
int sum(int a[], int b){
int c=0;
for(int i=0; i<b; i++){
c += a[i];
}
return c;
}
int main(){
int a[] = {1,2,3,4,5};
int b = sizeof(a)/sizeof(int);
cout << sum(a, b) << endl; //----------
return 0;
}
the function sum
takes the values inside the array and adds them. what I want to know is if I can call the array by value and not by reference, that is, change sum(a, b)
by sum({1,2,3,4,5}, b)
without having to create the variable.
As of C++11, you can use
std::initializer_list< >
:Note that you can't use the indirection operator this way
[]
: you have to iterate through your list of numbers using iterators; Which, in conjunction with range-based-for , really makes the code a lot easier to write and read.Note also that both usages are not equivalent . If the function expects a pointer, you can't pass it a
initializer_list
. And vice versa. Although this is simple to fix using function overloading:No, You can not. Arrays cannot be passed by value since they decay to a pointer as a parameter, we can see it in this example:
The code above shows:
So if we try to create and call the function
sum
passing an array by value:We get the following error:
The array passed by value decays to a pointer and you cannot use an initialization list to initialize a pointer. But, contrary to what you think , passing the array as a constant reference solves the problem:
You can see the code working in Try it online!. If you want no limit on the number of elements, use a template:
One way to solve your doubt is using functions with variable arguments:
You need to include the header
cstdarg
. You can use all the known parameters, and at the end put the ellipses...
, which will be replaced by the unknown ones.One limitation is that you have to indicate the number of parameters that are going to go. This can be done by using one of the parameters as information, or by putting a value at the end indicating that it no longer has to consider any more parameters. There also has to be a "normal" parameter, you can't just put the ellipses.
I put both versions. In
sumarA
the known parameter it is the first addend, and it is putnullptr
to indicate that it is no longer necessary to continue. In the second versionsumarB
, the known parameter indicates the number of addends, and will be used to iterate over the unknown parameters.You need to include the macros
va_list
,va_start
andva_end
http://c.conclase.net/curso/?cap=020b#PAR_VARIABLES
either
http://www.cplusplus.com/reference/cstdarg/va_arg/