+ 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 ?
8 ответов
+ 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
+ 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
+ 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.
+ 1
like this?
#include <iostream>
int main()
{
int c;
{
c = 5;
}
{
std::cout << c; // 5
}
return 0;
}
+ 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.
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 ??
0
I dont know c just re write the question for a compatriot. Anyway thank you for your response ☺