I'm reading C++ Primer and in section 6.2 it says:
"Parameter initialization works the same way as variable initialization."
Yet when I do:
void foo(char* args[]) {return;}
int main() {
char* args[]={"asd","dsa"}; // ok.
foo({"asd","dsa"}); // error.
}
Why is that?
As @T.C. pointed out in the comments, the args in the function argument is converted to a char** because functions can't take arrays as an argument. Since you can't do
char **asd={"asd","dsa"};
the code is illegal. My confusion came from the fact that
char* args[]={"asd","dsa"};
char **asd=args;
is legal.
It is generally possible to take advantage of the new initialization syntax and semantics to use anonymous arrays as arguments, but you will have to jump through a few hoops. For example
typedef const char *CC2[2];
void foo(const CC2 &a) {}
int main() {
foo({ "asd", "dsa" });
}
However, in your case this technique will not help because you are requesting an array-to-pointer conversion on a temporary array. This is illegal in C++.
typedef int A[2];
const A &r = A{ 1, 2 }; // reference binding is OK
int *p = A{ 1, 2 }; // ERROR: taking address is not OK
So, if you really want to do something like this, you can do the following
template <size_t N> void foo(const char *const (&args)[N]) {}
int main() {
foo({ "asd", "dsa" });
}
but that is not exactly what you had in mind originally.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With