Velocity Reviews

Velocity Reviews (http://www.velocityreviews.com/forums/index.php)
-   C Programming (http://www.velocityreviews.com/forums/f42-c-programming.html)
-   -   Re: Passing aggregate directly to function (http://www.velocityreviews.com/forums/t962205-re-passing-aggregate-directly-to-function.html)

James Kuyper 06-27-2013 03:40 PM

Re: Passing aggregate directly to function
 
On 06/27/2013 10:55 AM, Guillaume Dargaud wrote:
> Hello all,
> I have a colleague who was trying to do something like this, it wouldn't
> compile and I couldn't come with a reason as to _why_ you can't do it:
>
> void Func(char* Array[]) { ... }
>
> Func( {"aaa", "bb"} );


In other contexts, {"aaa", "bbb"} could be the initializer of an array
of char* objects. It could also be the initializer for a two-dimensional
array of char, so long as the second dimension is at least 3. However,
it is not, itself, an array, and can't be used as such. In this context,
it's just a syntax error.

> Func( {"c"} );
> ...
>
> Using an intermediate variable of course works:
> char* tmp[]={"aaa", "bb"};
> Func( tmp );
>
> So, is there any way to do it directly ? And if not why ?


C99 added the concept of compound literals, which is basically an
extension of the idea of string literals, which allows you to do
something similar to what you want, with slightly different syntax:

Func((char *[]){"aaa", "bbb"});

Internally, the meaning of the above code is exactly the same as your
version using tmp, except that in this case, the temporary object is
nameless. The temporary object's lifetime ends at the end of the
enclosing block. One reason why the syntax is different can be
understood if you consider this alternative:
Func2((char[][4]){"aaa", "bbb"});

This is equivalent to
char tmp[][4] = {"aaa", "bbb"};
Func2(tmp);

which is significantly different than the other version. With the syntax
you're suggesting, it wouldn't be possible to make that distinction.



All times are GMT. The time now is 07:05 AM.

Powered by vBulletin®. Copyright ©2000 - 2014, vBulletin Solutions, Inc.
SEO by vBSEO ©2010, Crawlability, Inc.