Question

CODE ONE #include #include using namespace std; string x =" I am global"; // Global x...

CODE ONE

#include
#include


using namespace std;

string x =" I am global"; // Global x

int main()
{
string x = " I am local"; // Local x
cout< cout<<::x<

return 0;
}

CODE TWO
#include
#include

using namespace std;

string str = "i am global ";// global

int main()
{


string srt = "i am local to main() ";//local to main()

cout << str << "---" << ::str << "\n";// LINE 5555.
int x=5;

int y=6;
  
if (y>5)
{
string str ="i am local to if block";//local to " if " block statement
cout << str<< "---" << ::str<< "\n";// LINE 6666 prints "i am local to if block", and "i am global", respectively.
return 0;

}

Hello. I have a question about the two given codes above.

RULE 1

From what I understand, if we have global and local variables with the SAME name,  preference ( operation like cout<) is given to the local variable instead of the global one with the assumption that local variable is inside the scope of some functions such as main().

This is true for CODE ONE. To print the global variable, we can use the scope resolution operator: : as shown in CODE ONE. The output is "I am local --- I am global".

RULE 2

For sub-block like "if", the rule is this = the scope resolution operator will give preference ONLY to the global variable, not to the local variable inside the main(), " I am local to main ". as shown in CODE TWO.

However, in CODE TWO, LINE 5555, the result seems to contradict rule RULE 1.  

LINE 5555) prints " i am global ---- i am global ". I was expecting it to print "i am local to main --- i am global".

Line 6666 CODE TWO prints "i am local to if block --- i am global".

WHY THE OUTPUT IS NOT "i am local to main --- i am global". since "i am local to main" is declared inside the main function ????

THANK YOU IN ADVANCE FOR ANY HELPFULL EXPLANATION.

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Because your String variable is srt and NOT str

string srt = "i am local to main() ";//local to main()

When I change srt to str,It gives correct output and your understanding is CORRECT..


SEE IMAGE,

PLEASE COMMENT if there is any concern.

==============================

Add a comment
Know the answer?
Add Answer to:
CODE ONE #include #include using namespace std; string x =" I am global"; // Global x...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT