Search code examples
c++for-loopvariablesdeclarationstdvector

Why is this C++ working? (declaration/definition of variables)


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()

Solution

  • 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?