C/C++ Printing Int i in If Portion of C++ Code

  • Thread starter Thread starter Rainier9
  • Start date Start date
  • Tags Tags
    C++ Urgent
AI Thread Summary
To print the local variable `i` with a value of 5 inside the `if` block without changing the variable names, the current code's scope resolution needs to be addressed. The existing declaration of `int i = 9;` within the `if` block hides the local `int i = 5;` from the `main` function, leading to the output of the global variable `i`, which is 7. To resolve this, the code should utilize the scope resolution operator correctly. By declaring the variable as `int i` without an initializer in the `if` block, the program can access the local variable `i` from `main`, allowing it to print the desired value of 5.
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.
 
Technology 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
 
Dear Peeps I have posted a few questions about programing on this sectio of the PF forum. I want to ask you veterans how you folks learn program in assembly and about computer architecture for the x86 family. In addition to finish learning C, I am also reading the book From bits to Gates to C and Beyond. In the book, it uses the mini LC3 assembly language. I also have books on assembly programming and computer architecture. The few famous ones i have are Computer Organization and...
I have a quick questions. I am going through a book on C programming on my own. Afterwards, I plan to go through something call data structures and algorithms on my own also in C. I also need to learn C++, Matlab and for personal interest Haskell. For the two topic of data structures and algorithms, I understand there are standard ones across all programming languages. After learning it through C, what would be the biggest issue when trying to implement the same data...
Back
Top