I want a piece of code which does not involve loops but automatically generates some C++ code.
I have an const int d
, and from this I want to write d lines of code to access an array. So for instance
for(int k=0; k<d;++k){
// do something to myarryay[k];
}
but I don't want to write this in a for loop. I want the complier to execute as if the following lines of code was written:
do something to myarray[0]
do something to myarray[1]
.
.
.
do something to myarray[d]
Can anyone give me a suggestion on some code that does this?
Thanks in advance.
Are you sure you need to do this manually? This is an optimization known as loop unrolling. At high enough optimization levels, your compiler will do it for you, and possibly better than you can, since a good optimizing compiler will take into account the tradeoffs (reduced instruction cache locality, for one).
You should rarely need to manually unroll a loop (I'd say never, but if you're working on something with crazy performance requirements and you think you can one-up the compiler optimizer, then perhaps you might manually unroll a loop).
If you do need to do this for some reason, it's quite straightforward with the help of the preprocessor:
#include <boost/preprocessor.hpp>
#include <iostream>
void f(int x) { std::cout << x << std::endl; }
int main()
{
#define MYARRAY_COUNT 10
int myarray[MYARRAY_COUNT] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
#define GENERATE_ELEMENT_CASE(z, n, data) f(myarray[n]);
BOOST_PP_REPEAT(MYARRAY_COUNT, GENERATE_ELEMENT_CASE, x)
#undef GENERATE_ELEMENT_CASE
#undef MYARRAY_COUNT
}
The expanded main()
function looks like:
int main()
{
int myarray[10] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
f(myarray[0]); f(myarray[1]); f(myarray[2]); f(myarray[3]); f(myarray[4]);
f(myarray[5]); f(myarray[6]); f(myarray[7]); f(myarray[8]); f(myarray[9]);
}