Search code examples
c++scopevariable-declarationobject-initialization

C++ how to declare a "complex" object inside a loop?


edit: As mentioned by @HolyBlackCat "If you need it to retain it's [a variable's] value between iterations, it has to stay outside." This is of course true of even primitive types, eg. int. So this question is actually just noise, sorry.

I'm trying to get my head around how to be consistent when declaring objects, the "declare variable inside or outside loop?" issue for variables that are only used inside a loop. See eg. Declaring variables inside loops, good practice or bad practice?.

Consider the below examples. Let V be an object which has a default constructor.

                                  // Example 1
std::vector<int> V;               // Works as intended
for (int i=0; i<2; i++) {         // ...but V should be declared inside loop(?)
    V.push_back(i);
    // V used only inside loop
}                                 
                                  // Example 2 
for (int i=0; i<2; i++) {         // OK Syntax, Wrong Semantics
    std::vector<int> V;           // V is "created" anew in each loop-step
    V.push_back(i);
    // V used only inside loop         
}
                                  // Example 3
for (int i=0; i<2; i++) {         // Syntax Error, other syntax possible?
    std::vector<int> V.push_back(i);
    // V used only inside loop 
}

Example 1: Defines the approximate semantics im looking for - besides that V is local to the loop and I would prefer to define V inside the loop.

Example 2: Defines V inside the loop but also creates it anew in each loop-step, this is NOT the desired semantics.

Example 3: "Nice try" exploration of syntax - Im trying to declare and "immediately use" the object V. This is illegal syntax.

If, at the end of the day, many types of objects are most elegantly declared outside the loop (as it would seem to be the case with V in the example; otherwise, if declared inside the loop, the declaration would have to be somehow "guarded") then i might just lean to declaring everything outside the loop, just before the loop, instead of inside the loop...

Please give me advice on this issue, how to get the semantics of Example 1 but with V declared inside the loop (if possible).


Solution

  • Yes, you can do this:

    std::vector<int> V{i}; 
    

    which initializes the vector V with the value i when it's declared.


    On the other hand, neither of your loops are actually doing anything useful. You are redeclaring V inside the loop every time, so previous push_backs are not visible. Also, V is not usable outside the scope of the for loop.

    It seems that what you are trying to do is fill a vector with counting numbers. The easy way to do that is:

    std::vector<int> V(2);
    std::iota(V.begin(), V.end(), 0);