[Solved] Declare variables inside loops the right way?


As mentioned by πάντα ῥεῖ in the comments, you can’t create new variable names dynamically at runtime in C++. All variable names must be known at compile-time. What you need to do here is use array indices instead.

For example, change somedata and Do to std::vectors. Something like this:

std::vector<bool> Do(5); // contains 5 bools, all initialized to false

for (unsigned int i = 0; i < something.size(); i++) {
        Do[i] = bool_function(somedata[i]);
}

It’s worth noting that std::vector<bool> is optimized for space: each element will occupy one bit, instead of sizeof(bool). This is okay for non-performance-critical stuff.

1

solved Declare variables inside loops the right way?