Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I do foo({"asd","asd1"}) with foo(char* args[])?

Tags:

c++

function

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?

like image 515
4nt Avatar asked Jul 26 '15 23:07

4nt


2 Answers

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.

like image 106
4nt Avatar answered Oct 02 '22 06:10

4nt


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.

like image 32
AnT Avatar answered Oct 02 '22 06:10

AnT