为什么这个 C++ 工作?(变量的声明/定义)

vel*_*s14 1 c++ variables for-loop declaration stdvector

为什么我可以在 for 循环的每次迭代中在 for 循环 [for (auto val: k0L){...}] 中声明和定义 3 个变量?当我执行 g++ code.cpp 时,编译器不会抱怨。我知道一个变量只能声明一次。我知道我不能写 int a = 5; int a = 6; 在 main() 范围内。但是,这就是我在 for 循环中所做的。谢谢!

#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()
Run Code Online (Sandbox Code Playgroud)

Kon*_*lph 6

因为这是如何在范围C ++的工作:这些变量的范围是在体内for循环。换句话说:它们是在每次循环迭代中创建的,并且一直存在到同一次迭代结束。

即使多次调用函数,它也完全等同于如何在函数内声明局部变量:

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

int main() {
    f(2);
    f(2);
}
Run Code Online (Sandbox Code Playgroud)

这当然不会让您感到惊讶,您不认为a内部f以某种方式重新定义了吗?