I have two variables and I want to work with the bigger and the smaller one differently.
My approach:
a = 1;
b = 2;
if (a >= b){
int c = a;
int d = b;
}
else{
int c = b;
int d = a;
}
I obtained an error of unused variable and when I try to use c
and d
later, it says
c
could not be resolved
Is there a way to solve this?
In both cases c
and d
are scoped to the braces in the if
else
block, so you can't access them outside that.
You need something of the form
int c, d;
if (a >= b){
c = a;
d = b;
} else {
c = b;
d = a;
}
As other have pointed out the issue here is where you declare the variables. You cannot use them outside of the scope they are declared in so you get an error.
If you can use C++17 then you can fix the code by using std::minmax
and a structured binding like
int main()
{
int a = 5, b = 10;
auto [min, max] = std::minmax(b, a);
std::cout << min << " " << max;
}
which is really nice because now you don't have variables that are uninitialized for any amount of time.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With