1

Why can I declare and define 3 variables inside the for-loop [for (auto vall: k0L){...}], at each iteration of the for-loop? The compiler doesn't complain when I do g++ code.cpp. I know a variable can be declared only once. I know I cannot write int a = 5; int a = 6; inside the main() scope. However, this is what I am doing inside that for-loop. Thank you!

#include <iostream>
#include <vector>
#include <fstream>
#include <math.h>
#include <algorithm>

#define PI 3.14159265

std::vector<double> linspace (double start, double end, size_t points) { // will be used in main(), details of this function are not important.
    std::vector<double> res(points);
    double step = (end - start) / (points - 1);
    size_t i = 0;
    for (auto& e: res) {
        e = start + step * i++;
    }
    return res;
}

int main() {

    std::vector<double> k0L = linspace (0,20, 10000); // a linearly spaced vector with 10000 values between 0,20
    std::vector<double> f_ra; 

    **// QUESTION : Why can I declare and define tau, phi_of_tau, to_push_back, at each iteration of the following for-loop?** 
    for (auto vall: k0L) {
        double tau = pow(vall, (1./3.)) * sin(20.0*PI/180.0);  // something1
        double phi_of_tau = 2.1 * tau * exp(- (2./3.) * pow(tau,3) );  // something2
        double to_push_back = 0.5 * pow(phi_of_tau, 2); // something_total, composed of something1 and something2
        f_ra.push_back(to_push_back); // equivalent to instruction below
        // f_ra.push_back(0.5 * pow(2.1 * (pow(vall, (1./3.)) * sin(30.0*PI/180.0)) * exp(- (2./3.) * pow((pow(vall, (1./3.)) * sin(20.0*PI/180.0)),3)), 2));    
    }

    // Write values to a file
    std::ofstream myfile("fra_vs_k0L_30degrees.dat");
    for (auto i=0; i<= f_ra.size(); i++) {
        myfile << k0L[i] << " " << f_ra[i] << std::endl;
    }

return 0;
} // END main()
velenos14
  • 534
  • 4
  • 13

4 Answers4

6

Because that’s how scopes in C++ work: the scope of these variables is the body of the for loop. In other words: they are created inside each loop iteration and live until the end of that same iteration.

It’s entirely equivalent to how you can declare local variables inside a function even if you call a function multiple times:

int f(int x) {
    int a = x * 2;
    return a;
}

int main() {
    f(2);
    f(2);
}

Surely this does not surprise you, and you don’t think that a inside f is somehow redefined?

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
2

This is due to scope. All these variables are only available in the for loop. If you have this code

if(true) {
  int a = 1;
}
// notice a is not defined here, only in the if
if(true) {
  int a = 2;
}

It wont complain either.

DownloadPizza
  • 3,307
  • 1
  • 12
  • 27
1

C++ allows you declare/define variables within a loop. The memory for the variable is allocated once at the beginning of the loop and because those variables were declared within the loop their scope is limited to within that loop.

This can be good practice since limiting the scope of variables is generally the right call and makes for easier debugging. It should be noted though that the variables are not expected to retain their values between loops and in your specific example their values are reinitialized each time. Since you have some decently complex math happening to initialize those variables, this might be a meaningful drain on performance since those calculations are done to initialize the variables each loop. Since it looks like those variables hold constant values, you may be better of in your case to define the variables just outside the scope of the loop so the computations are only completed once. Hope that was helpful!

The following pages also address this question very well :)

Declaring variables inside loops, good practice or bad practice?

https://softwareengineering.stackexchange.com/questions/296721/is-it-good-to-define-a-variable-inside-a-loop

  • Thank you very much! The variables' values change at each iteration of the for loop because vall is different at each iteration of the for-loop. But I noted and will keep in mind your info @ unnecessary repeating calculations. – velenos14 Feb 09 '21 at 18:17
0

While other answers related to for-loop syntax are correct, but I think the OP is asking about C++11's range-based for-loop syntax that is making him/her worried.

This for (auto a : container) {...} is the C++11's range-based for-loop syntax, which is for iterating over a container data-structure with a reference a on each step, with the keyword auto meaning that the type of a will be whatever the container objects' type is.

More details can be found here: https://en.cppreference.com/w/cpp/language/range-for

Hack06
  • 963
  • 1
  • 12
  • 20