Using a variable value in another block in C/C++ | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Using a variable value in another block in C/C++

Hi If i declared a variable in main and for example i get a value to it in a while block . Is there a way to use that value outside while block ?

4th Dec 2020, 11:07 PM
reza jannati
reza jannati - avatar
7 Answers
+ 1
That depends on where you wrote the while-loop I guess, if the variable and the while loop are both in main function, then it is possible. To be more descriptive and clear, I suggest you to share your code link here for the community to see. Follow the below guide to share that code in question 👍 https://www.sololearn.com/post/75089/?ref=app
5th Dec 2020, 3:01 AM
Ipang
+ 3
Ipang do they really need to be in main()?! correct me if i misunderstood you. #include <iostream> void v(int& t) { int i = 0; while (i < 100) { if (i == 50) { t = 456; } i++; } } int main() { int c; v(c); std::cout << c; // 456 return 0; } https://code.sololearn.com/cQX42D9E5eVK/?ref=app
5th Dec 2020, 3:20 AM
Flash
+ 1
I don't think there is. Even there is, I would rather name the variable differently because it causes ambiguity, decreasing the readability of the code.
4th Dec 2020, 11:42 PM
你知道規則,我也是
你知道規則,我也是 - avatar
+ 1
like this? #include <iostream> int main() { int c; { c = 5; } { std::cout << c; // 5 } return 0; }
5th Dec 2020, 2:42 AM
Flash
+ 1
Flash Quoting the original post: "If i declared a variable in main and for example i get a value to it in a while block . Is there a way to use that value outside while block?" Here's my interpretation of it in code ... int main() { int value = 5; // declare var in main while( value < 10 ) { value++; // get its value in while-loop block } // a way to use value outside while-loop block std::cout << value; return 0; } I had asked the OP to share his code to avoid misunderstanding and to be clear with what was meant by the question. I'll just wait for the OP's code, cause the question didn't sound too clear.
5th Dec 2020, 3:35 AM
Ipang
0
Is that possible to declare a variable and assigning value to it , in main section. And use it outside the main block? # reza joon zabanam bekhon ;) Man java midonam . Va in emkan pazir nist dar java ! Daghighan mikhay chikar koni ?? Chera meghdare dakhele main oo biron mikhay ?? Masaln mikhay bebari to class ?? To method dige ??
4th Dec 2020, 11:35 PM
Armin Akhavan
Armin Akhavan - avatar
0
I dont know c just re write the question for a compatriot. Anyway thank you for your response ☺
4th Dec 2020, 11:49 PM
Armin Akhavan
Armin Akhavan - avatar