Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Urgent help! C++ question!

  1. Jan 20, 2012 #1
    I need to print the int i right next to the main, but I need to do it while Im in the if portion of the following code:

    Code (Text):

    int i = 7;
    int main()
    int i = 5;
    cout << ::i;
    int i =9;
    cout << ::i<<endl;

        return 0;
    Right now it prints 7. I need it to print 5 without changing the variable name.
  2. jcsd
  3. Jan 20, 2012 #2

    I like Serena

    User Avatar
    Homework Helper

    Hi Rainier9! :smile:

    The "int i=9" hides the "int i=5" in a way that it is inaccessible using the name "i".
    The language has been designed this way.
  4. Jan 21, 2012 #3
    You declare "int i = 9" as a global before main() and then try to name a new "int i" that is set to 5. I am surprised you didn't get at least a warning about it when you compiled.
    The global int i will always be processed for any statement or function that calls i.
    To fix it just declare i. like this: "int i"
    then your program should be fine.
  5. Jan 22, 2012 #4
Share this great discussion with others via Reddit, Google+, Twitter, or Facebook