用于变量范围的 C++ [英] C++ for variable scope

查看:41
本文介绍了用于变量范围的 C++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 C++ 新手,遇到了这个:

I'm new to c++ and came across this:

    for (int i=0 ; i<500 ; i++) {
        //to do
    }

    int i;
    std::cin >> i;

更新:使用 Visual Studio 2010(及其使用的编译器),for 循环外的 i 在调用 cin >> i 后的值为 500;我正在使用 Visual Studio 调试器查看这些值 <<(这就是问题所在 - 谢谢格雷格)

UPDATE: Using visual studio 2010 (and the compiler it uses) the i outside the for loop has the value 500 AFTER the call to cin >> i; I am looking at the values using the Visual Studio debugger << (this is the problem - thanks Greg)

现在我期待

a) 整数 i;在 for 循环和 int i=0 之外;成为不同的变量,即 for 循环 i 一旦大括号关闭就超出范围

a) the int i; outside the for loop and the int i=0; to be different variables i.e. the for loop i to go out of scope once the braces close

b) 一旦我意识到它没有超出范围,我想知道为什么它没有被 cin 覆盖.

b) once I realized that it wasn't going out of scope I wondered why it was not getting over-written by the cin.

我认为 b) 是故意的(尽管我在 Bjarne Stroustrup 的关于 c++ 的书中找不到它的页面)但我确信它在同一本书中声明变量在它们所包含的大括号内具有作用域.

I think b) is intentional (though I'm having trouble finding the page its on in Bjarne Stroustrup's book on c++) but I am sure it states in the same book that variables have scope within the braces they are enclosed in.

在大多数其他语言中,我知道在 for 构造中声明变量时,它们被认为是在 for 循环的大括号中,但在 C++ 中,情况似乎并非如此.

In most other languages I know when declaring variables in the for construct they are considered to be in the braces of the for loop but in c++ this doesn't seem to be the case.

是这种情况吗?这是否特定于 for 循环,或者是否有其他情况会发生这种情况(我想不出其他任何情况,但嘿,我是新人)

Is this the case and is this specific to the for loop or are there any other cases where this happens (I can't think of any other but hey I'm new)

谢谢

推荐答案

在某些情况下,尤其是在同一个函数中有两个同名不同变量的情况下,您不能总是相信调试器会给出你更正信息.如果您要求 i 的值,调试器可能不知道您指的是哪个 i.根据您的描述,听起来编译器为 i 的每个不同实例分配了两个不同的内存位置.

In some situations, particularly in this case where you have two different variables in the same function with the same name, you can't always trust the debugger to give you correct information. If you're asking for the value of i, the debugger might not know exactly which i you are referring to. From what you have described, it sounds like the compiler has allocated two different memory locations for each different instance of i.

我经常使用这个原则如有疑问,请打印更多.如果您使用 std::cout <<i,那么您应该看到 iactual 值,该值在您打印输出点的范围内.

I often use the principle When in doubt, print more out. If you use std::cout << i, then you should see the actual value of i that is in scope at the point where you print the output.

这篇关于用于变量范围的 C++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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