簡體   English   中英

C ++中的全局變量和局部變量

[英]Global and local variables in C++

我是C ++的新手,在打印局部變量和全局變量時遇到了一些問題。 考慮這段簡單的代碼:

#include <cstdlib>
#include <iostream>

using namespace std;

/*
 * 
 */
int x = 10; // This x is global
int main() {
    int n;
    { // The pair of braces introduces a scope  
    int m = 10;    // The variable m is only accessible within the scope
    cout << m << "\n";

    int x = 25; // This local variable x hides the global x
    int y = ::x; // y = 10, ::x refers to the global variable x
    cout << "Global: " << y << "\n" << "Local: " << x << "\n";
    {
        int z = x; // z = 25; x is taken from the previous scope
        int x = 28; // it hides local variable x = 25 above
        int t = ::x; // t = 10, ::x refers to the global variable x
        cout << "(in scope, before assignment) t = " << t << "\n";
        t = x; // t = 38, treated as a local variableout was not declared in this scope
        cout << "This is another hidden scope! \n";
        cout << "z = " << z << "\n";
        cout << "x = " << x << "\n";
        cout << "(in scope, after re assignment) t = " << t << "\n";
    } 
    int z = x; // z = 25, has the same scope as y
    cout << "Same scope of y. Look at code! z = " << z;
    }
    //i = m; // Gives an error, since m is only accessible WITHIN the scope

    int m = 20; // This is OK, since it defines a NEW VARIABLE m
    cout << m;

    return 0;
}

我的目標是在各種范圍內實現變量的可訪問性,然后打印它們。 但是,我無法弄清楚為什么當我嘗試打印最后一個變量z ,NetBeans會返回輸出2025 這是我的示例輸出:

10
Global: 10
Local: 25
(in scope, before assignment) t = 10
This is another hidden scope! 
z = 25
x = 28
(in scope, after re assignment) t = 28
Same scope of y. Look at code! z = 2520
RUN FINISHED; exit value 0; real time: 0ms; user: 0ms; system: 0ms

希望有人能幫我理解發生的事情! :)

是不是z保持值2520是你在打印z和打印m之間省略添加新的行操作符的事實...

你在做:

cout << "Same scope of y. Look at code! z = " << z;
}

int m = 20;  
cout << m;

但你應該這樣做:

std::cout << "Same scope of y. Look at code! z = " << z << std::endl;
}

int m = 20;  
std::cout << m << std::endl;

如果你只是遵循相同的標記輸出和做類似的標准

std::cout << "M is: "<<m << std::endl;

你會通過觀察輸出更快地發現問題:

25M is: 20 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM