为什么此C ++可以工作?(变量的声明/定义) [英] Why is this C++ working? (declaration/definition of variables)

查看:46
本文介绍了为什么此C ++可以工作?(变量的声明/定义)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

推荐答案

因为这是C ++的作用域工作方式:这些变量的作用域是 for 循环的主体.换句话说:它们是在每次循环迭代中创建的,并且一直存在到同一迭代结束为止.

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);
}

这肯定不会令您感到惊讶,并且您不认为重新定义了 f 中的 a 吗?

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

这篇关于为什么此C ++可以工作?(变量的声明/定义)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆