Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C/C++ arrays assignment

Sample code:

int ar[3];
............
ar[0] = 123;
ar[1] = 456;
ar[2] = 789;

Is there any way to init it shorter? Something like:

int ar[3];
............
ar[] = { 123, 456, 789 };

I don't need solution like:

int ar[] = { 123, 456, 789 };

Definition and initialization must be separate.

like image 335
kyrylomyr Avatar asked Mar 21 '26 05:03

kyrylomyr


1 Answers

What you are asking for cannot be done directly. There are, however different things that you can do there, starting from creation of a local array initialized with the aggregate initialization and then memcpy-ed over your array (valid only for POD types), or using higher level libraries like boost::assign.

// option1
int array[10];
//... code
{
   int tmp[10] = { 1, 2, 3, 4, 5 }
   memcpy( array, tmp, sizeof array ); // ! beware of both array sizes here!!
}  // end of local scope, tmp should go away and compiler can reclaim stack space

I don't have time to check how to do this with boost::assign, as I hardly ever work with raw arrays.

like image 112
David Rodríguez - dribeas Avatar answered Mar 23 '26 19:03

David Rodríguez - dribeas