Re: A89: Arrays in C
[Prev][Next][Index][Thread]
Re: A89: Arrays in C
> Really? I've tried to do that w/ Borland C++ in my CS class at school and
> it didn't work. When I asked my CS teacher, he said it was impossible...
> > and yes, you can instead do this:
> >
> > int a[]={9,2,7};
I think I know what your problem is with that.
What Robin's talking about is an initialiser, as in this:
int x[ 3 ] = { 1, 2, 3 };
void func()
{
...
}
where x is a global variable and is initialised.
ANSI C does not allow initialisation of auto variables:
void func()
{
int x[ 3 ] = { 1, 2, 3 };
...
}
is not valid ANSI but [ of course :-) ] is valid gcc.
(In fact, gcc allows you any expression in initialisers.)
Now this is not valid in ANSI *or* gcc: [ :-( ]
void func()
{
int x[ 3 ];
...
x = { 1, 2, 3 };
}
On the other hand, gcc allows you to create dynamic arrays, so this is
actually valid (not in ANSI, though):
int func( int select )
{
return ((int [3]) { 3, 6, 9 })[ select ];
}
Using the dynamic array creation you can assign values to an array,
albeit often slower than doing it piece by piece:
void func()
{
int x[ 3 ];
memcpy( x, (int [3]) { 1, 2, 3 }, sizeof( x ) );
}
The above is quicker than doing
x[ 0 ] = 1; x[ 1 ] = 2; x[ 2 ] = 3;
because all initialisers are constants.
However,
void func()
{
int x[ 3 ];
memcpy( x, (int [3]) { foo(), bar(), baz() }, sizeof( x ) );
}
will be slower than
x[ 0 ] = foo();
x[ 1 ] = bar();
x[ 2 ] = baz();
because the compiler has to generate a temporary array then copy it to
x, that is, what it will do is this:
temp[ 0 ] = foo();
temp[ 1 ] = bar();
temp[ 2 ] = baz();
memcpy( x, temp, sizeof( x ));
which is obviously slower.
Regards,
Zoltan
References: