Printing Int i in If Portion of C++ Code

  • Context: C/C++ 
  • Thread starter Thread starter Rainier9
  • Start date Start date
  • Tags Tags
    C++ Urgent
Join the discussion
Ask a follow-up here, or get your own question answered by working scientists, mathematicians and engineers — people, not an autocomplete.
Real named experts · corrections over time · the nuance an AI answer skips
3 replies · 2K views
Rainier9
Messages
32
Reaction score
0
I need to print the int i right next to the main, but I need to do it while I am in the if portion of the following code:

Code:
int i = 7;
int main()
{
int i = 5;
cout << ::i;
if(1)
{
int i =9;
cout << ::i<<endl;
}

    return 0;
}

Right now it prints 7. I need it to print 5 without changing the variable name.
 
Physics news on Phys.org
Rainier9 said:
I need to print the int i right next to the main, but I need to do it while I am in the if portion of the following code:

Code:
int i = 7;
int main()
{
int i = 5;
cout << ::i;
if(1)
{
int i =9;
cout << ::i<<endl;
}

    return 0;
}

Right now it prints 7. I need it to print 5 without changing the variable name.

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.
 
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.
Paul